How do I allow null for a foreignkey? I have a through
and belongsToMany
association:
Shelf
belongsToMany(Book, { through: Library, as: "Books"});
Book
belongsToMany(Shelf, { through: Library, as: "Shelves"});
Library
section: DataTypes.STRING,
// ... other fields
I would like to record a null
on the bookId
in Library
:
Library.create({
section: "blah",
bookId: null,
shelfId: 3
});
Since Sequelize automatically creates the bookId
and shelfId
in the join table Library
, how would I specify that I want to allow a null
on the bookId
foreignkey in Library
?
We will allow null on foreign keys (the default), meaning that a Ship can exist without a Captain and vice-versa.
Sequelize association methods also accept an options object that you can use to configure the details of the association. For example, you can change the foreign key name on the table by adding the foreignKey property: User. hasOne(Invoice, { foreignKey: "invoice_creator", // UserId -> invoice_creator });
The target key is the column on the target model that the foreign key column on the source model points to. So in the following cases, which is the target? Route. belongsTo(models.
Creating associations in sequelize is done by calling one of the belongsTo / hasOne / hasMany / belongsToMany functions on a model (the source), and providing another model as the first argument to the function (the target). hasOne - adds a foreign key to the target and singular association mixins to the source.
I am no expert on node.js
nor sequelize.js
, but with one search in google I got the official documentation. You might need to pay some attention to this part of the code in the documentation:
Library.hasMany(Picture, {
foreignKey: {
name: 'uid',
allowNull: false
}
});
It seems you need to specify the {foreignKey: {name: 'bookId', allowNull: true} }
in Library
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With