fanhats
fanhats

Reputation: 797

allow null value for sequelize foreignkey?

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?

Upvotes: 17

Views: 26325

Answers (2)

Moshe G
Moshe G

Reputation: 542

By default, the Sequelize association is considered optional. If you would like to make the foreign key required, you can set allowNull to be false.

Foo.hasOne(Bar, {
  foreignKey: {
    allowNull: false
  }
});

See the docs

Upvotes: 2

tftd
tftd

Reputation: 17032

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.

Upvotes: 27

Related Questions