Tal vez esta es una solución simple, pero parece que no puedo entender qué estoy haciendo mal aquí.
Tengo una tabla que enumera todos los estados Modelo:
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`, }, }, }Migración:
await knex.schema.createTable(tableNames.state, (table) => { table.increments().primary().notNullable() table.string('name', 100).notNullable()Modelo de tabla de usuario:
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`, }, } } }Migración de tabla de usuario:
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') }) Ahora el problema: quiero que la columna state_id sea anulable, ya que no todos los usuarios tendrán un estado asignado. Pero cuando intento insertar un usuario sin state_id, obtengo esto: insert or update on table \"user\" violates foreign key constraint \"user_state_id_foreign\" .
dos cosas que estas haciendo mal
state_id: {type: ['integer', 'null']}table.integer('state_id').unsigned().nullable()