带有Node js Sequelize一对一的postgresql允许模型1的多个实例与模型2的同一实例相关

postgresql with Node js Sequalize One-To-One allows multiple instances of model 1 to be related to the same instance of model 2

我正在尝试使用节点 js 和 sequalize 创建不同的模型关联,但我在创建一对一关联时遇到问题。

文档说使用 .hasOne() 和 .belongsTo() 来创建一对一。来自 sequalize 文档:

Foo.hasOne(Bar);
Bar.belongsTo(Foo);

导致以下 sql 语句:

CREATE TABLE IF NOT EXISTS "foos" (
  /* ... */
);
CREATE TABLE IF NOT EXISTS "bars" (
  /* ... */
  "fooId" INTEGER REFERENCES "foos" ("id") ON DELETE SET NULL ON UPDATE CASCADE
  /* ... */
);

现在是不是一对一关联应该有一个约束来防止多个 'Bars' 引用同一个 'Foo'?因为我在结果 sql 中看不到这样的约束,我已经尝试了代码,是的,我可以有多个 'Bars' 指向一个 'Foo',这使它成为一对一-很多不是吗?

同样来自文档的一对多关联,代码如下:

Team.hasMany(Player);
Player.belongsTo(Team);

导致以下 sql 语句:

CREATE TABLE IF NOT EXISTS "Teams" (
  /* ... */
);
CREATE TABLE IF NOT EXISTS "Players" (
  /* ... */
  "TeamId" INTEGER REFERENCES "Teams" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
  /* ... */
);

这与一对一生成的 sql 语句相同。我错过了什么吗?请有人帮忙。

我希望 'fooId' 列有一个独特的限制,以防止多个“条”与单个“foo”相关

奇怪的是 Foo.hasOne(Bar) 不足以创建任何约束来阻止多个 Bar 对象与同一个 Foo 对象相关联,至少在 version 6 of sequelize.但是,Foo 对象的实例方法有所不同,其中 Foo.hasOne(Bar)Foo.hasMany(Bar)(参见 the docs for associations)。具体来说,您将拥有:

Foo.hasOne(Bar)

fooInstance.getBar()
fooInstance.setBar()
fooInstance.createBar()

对比

Foo.hasMany(Bar)

fooInstance.getBars()
fooInstance.countBars()
fooInstance.hasBar()
fooInstance.hasBars()
fooInstance.setBars()
fooInstance.addBar()
fooInstance.addBars()
fooInstance.removeBar() fooInstance.removeBars()
fooInstance.createBar()

也就是说,可以将唯一约束添加到模型定义中。例如,

let Parent = sequelize.define('parent', {
        id: {
            type: DataTypes.INTEGER,
            allowNull: false,
            autoIncrement: true,
            primaryKey: true
        },
        name: DataTypes.STRING
    },
    {
        tableName: 'parents',
        timestamps: false
    })

let Child = sequelize.define('child', {
        id: {
            type: DataTypes.INTEGER,
            allowNull: false,
            autoIncrement: true,
            primaryKey: true
        },
        name: DataTypes.STRING,
        parentId: {
            type: DataTypes.INTEGER,
            references: {
                model: Parent,
                key: 'id'
            },
            unique: true
        }
    },
    {
        tableName: 'children',
        timestamps: false
    })

Parent.hasOne(Child, {
    foreignKey: 'parentId',
    sourceKey: 'id'
})
Child.belongsTo(Parent, {
    foreignKey: 'parentId',
    targetKey: 'id'
})

上面截取的导入部分是这样一行:

unique: true

这将导致:

CREATE TABLE IF NOT EXISTS "children" ("id"   SERIAL , "name" VARCHAR(255), "parentId" INTEGER UNIQUE REFERENCES "parents" ("id") ON DELETE CASCADE ON UPDATE CASCADE, PRIMARY KEY ("id"));