【问题标题】:allow null value for sequelize foreignkey?允许空值用于续集外键?
【发布时间】:2021-08-24 04:04:03
【问题描述】:

如何允许外键为空?我有一个throughbelongsToMany 关联:

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

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

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

我想在bookId 上录制null Library

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

由于 Sequelize 自动在连接表 Library 中创建 bookIdshelfId,我将如何指定我希望在 bookId 的外键上允许 null Library

【问题讨论】:

    标签: javascript node.js postgresql sequelize.js


    【解决方案1】:

    我既不是node.js 也不是sequelize.js 方面的专家,但是在谷歌中搜索一下我就得到了official documentation。您可能需要注意文档中的这部分代码:

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

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

    【讨论】:

    • 我试过了,但它仍然拒绝允许 null:{ through: Library, as: "Books", foreignKey: { name: 'bookId', allowNull: true }}null value in column "bookId" violates not-null constraint
    • 您尝试添加{foreignKey:{...}, constraints: false} 吗?
    • 注意:已批准 @farhan-yaseen 的更改,因为我在复制的代码中有一些拼写错误。谢谢!
    • 这个帖子我有点晚了,但我也经历了同样的事情,你们能指出我正确的方向吗?
    【解决方案2】:

    默认情况下,Sequelize 关联被认为是可选的。如果您想使外键成为必需,您可以将allowNull 设置为false

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

    See the docs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 1970-01-01
      • 2014-05-29
      • 1970-01-01
      • 2020-08-03
      • 2010-12-21
      相关资源
      最近更新 更多