objectionjs/knex是否可以使用可为null的外键



也许这是一个简单的修复,但我似乎不明白我在这里做错了什么。

我有一张表列出了所有的州型号:

static get jsonSchema() {
return {
type: 'object',
properties: {
id: { type: 'integer' },
name: { type: 'string', minLength: 1, maxLength: 100 },
},
}
}
static get relationMappings() {
return {
users: {
relation: Model.HasManyRelation,
modelClass: User,
join: {
from: `${tableNames.state}.id`,
to: `${tableNames.user}.state_id`,
},
},
}

迁移:

await knex.schema.createTable(tableNames.state, (table) => {
table.increments().primary().notNullable()
table.string('name', 100).notNullable()

用户表模型:

static get jsonSchema() {
return {
type: 'object',
properties: {
id: { type: 'integer' },
first_name: { type: 'string', minLength: 1, maxLength: 100 },
last_name: { type: 'string', minLength: 1, maxLength: 100 },
state_id: { type: 'integer', default: null },
},
}
}
static get relationMappings() {
return {
state: {
relation: Model.BelongsToOneRelation,
modelClass: State,
join: {
from: `${tableNames.user}.state_id`,
to: `${tableNames.state}.id`,
},
}
}
}

用户表迁移:

await knex.schema
.createTable(tableNames.user, (table) => {
table.increments().primary().notNullable()
table.string('first_name', 100).notNullable()
table.string('last_name', 100).notNullable()
table.integer('state_id').unsigned()
table
.foreign('state_id')
.references('id')
.inTable(tableNames.state)
.onDelete('SET NULL')
})

现在的问题是:我希望state_id列可以为null,因为不是每个用户都会有一个状态分配给他们。但是,当我尝试插入一个没有state_id的用户时,我得到的是:insert or update on table "user" violates foreign key constraint "user_state_id_foreign"

有两件事你做错了

json模式中的
  1. 将列定义为state_id: {type: ['integer', 'null']}
  2. 在用户迁移中使table.integer('state_id').unsigned().nullable()

最新更新