簡體   English   中英

允許空值用於續集外鍵?

[英]allow null value for sequelize foreignkey?

如何允許外鍵為空? 我有一個throughbelongsToMany關聯:

Shelf
    belongsToMany(Book, { through: Library, as: "Books"});

Book
    belongsToMany(Shelf, { through: Library, as: "Shelves"});

Library
    section: DataTypes.STRING,
    // ... other fields

我想在LibrarybookId上記錄一個null

Library.create({
    section: "blah",
    bookId: null,
    shelfId: 3
});

由於 Sequelize 自動在連接表Library創建bookIdshelfId ,我將如何指定我希望在LibrarybookId鍵上允許null

我不是node.jssequelize.js專家,但通過在谷歌中搜索,我得到了官方文檔 您可能需要注意文檔中的這部分代碼:

Library.hasMany(Picture, {
  foreignKey: {
    name: 'uid',
    allowNull: false
  }
});

看來您需要在Library指定{foreignKey: {name: 'bookId', allowNull: true} }

默認情況下,Sequelize 關聯被認為是可選的。 如果您想讓外鍵成為必需,您可以將allowNull設置為false

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

查看文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM