[v5] Preload nullable() foreign keys #1904
-
I'm using following DB migrations and models (demo but reproduces my problem): Migrationsxxx_User.ts public async up() {
this.schema.createTable(this.tableName, table => {
table.increments("id")
table.integer("setting_id").nullable().unsigned()
table
.foreign("setting_id")
.references("id")
.inTable("settings")
.onDelete("SET NULL")
.onUpdate("CASCADE")
})
} xxx_Setting.ts public async up() {
this.schema.createTable(this.tableName, table => {
table.increments("id")
table.string("key", 50).notNullable()
table.string("value", 50).notNullable()
})
} ModelsUser.ts export default class User extends BaseModel {
@column({ isPrimary: true })
public id: number
@column()
public settingId?: number
/// Relationships
@belongsTo(() => Setting)
public setting: BelongsTo<typeof Setting>
} Setting.ts export default class Setting extends BaseModel {
@column({ isPrimary: true })
public id: number
} Controllerpublic async userSettings() {
const user: User // User with `setting_id = null`
await user.preload("setting")
return {
user
}
} The problem occurs if i want to preload a But how do i set the default foreign key to |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 3 replies
-
Checking for existence before preloading bypasses the error: if(user.settingId) {
await user.preload("setting")
} Is this the intended way? |
Beta Was this translation helpful? Give feedback.
-
My suggestion is |
Beta Was this translation helpful? Give feedback.
-
I set directly on the model value to null and this work for me :) @column({ columnName: 'shopId' }) public shopId: number | null = null |
Beta Was this translation helpful? Give feedback.
My suggestion is
don't create a users table with a foreign key of a settings table
create a settings table with a foreign key of a users table
and on preload, it will not show any error