[英]allow null value for sequelize foreignkey?
如何允許外鍵為空? 我有一個through
和belongsToMany
關聯:
Shelf
belongsToMany(Book, { through: Library, as: "Books"});
Book
belongsToMany(Shelf, { through: Library, as: "Shelves"});
Library
section: DataTypes.STRING,
// ... other fields
我想在Library
的bookId
上記錄一個null
:
Library.create({
section: "blah",
bookId: null,
shelfId: 3
});
由於 Sequelize 自動在連接表Library
創建bookId
和shelfId
,我將如何指定我希望在Library
的bookId
鍵上允許null
?
我不是node.js
或sequelize.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.