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
?
Best Solution
I am no expert on
node.js
norsequelize.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:It seems you need to specify the
{foreignKey: {name: 'bookId', allowNull: true} }
inLibrary
.