Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 520
fanhats Avatar asked Feb 09 '15 01:02

fanhats


People also ask

Can a foreign key be null Sequelize?

We will allow null on foreign keys (the default), meaning that a Ship can exist without a Captain and vice-versa.

How do you set a foreign key in Sequelize?

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 });

What is Sequelize target key?

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.

What is Sequelize association?

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.


1 Answers

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.

like image 122
tftd Avatar answered Sep 18 '22 00:09

tftd