Sequelize's createXXXXX method doesn't seem to be adding the necessary foreign key.
This running the following code for these two models gives me a "notNull Violation: Seat.office_id cannot be null" error. The docs seem to indicate that that column should be automatically populated, no?
class Seat extends Model {
static init(sequelize) {
super.init(
{
id: {
autoIncrement: true,
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true,
},
office_id: {
type: DataTypes.INTEGER,
allowNull: false,
},
name: {
type: DataTypes.STRING,
allowNull: true,
},
},
{
sequelize,
tableName: "seat",
schema: "public",
timestamps: false,
indexes: [
{
name: "seat_pkey",
unique: true,
fields: [{ name: "id" }],
},
],
},
);
}
static associate(models) {
this.belongsTo(models.Office, {
foreignKey: "office_id",
as: "office",
});
}
}
class Office extends Model {
static init(sequelize) {
super.init(
{
id: {
autoIncrement: true,
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true,
},
title: {
type: DataTypes.STRING,
allowNull: true,
},
description: {
type: DataTypes.STRING,
allowNull: true,
},
},
{
sequelize,
tableName: "office",
schema: "public",
timestamps: false,
indexes: [
{
name: "office_pkey",
unique: true,
fields: [{ name: "id" }],
},
],
},
);
}
static associate(models) {
this.hasMany(models.Seat, {
foreignKey: "office_id",
as: "seats",
});
}
}
let office = await Office.findByPk(1);
let seat = await Seat.build({
name: "Test",
});
office.createSeat(seat);
can you try ...
let seat = await office.createSeat({ name: "Test"}); // Only pass the data object, no need to pass the instance ...
i don't think createSeat expects seat object