postgresql with Node js Sequalize一对一允许模型1的多个实例与模型2的同一个实例相关联.



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

文档说使用. hasone()和. belongsto()来创建一对一。来自序列化文档:

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
/* ... */
);

好了,现在是不是一个一对一的关联应该有一个约束,以防止多个'酒吧'引用相同的'Foo'?因为我在结果sql中看不到这样的约束,我已经尝试过代码,是的,我可以有多个"酒吧"指向一个"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.hasOne(Bar)Foo.hasMany(Bar)Foo对象上的实例方法是不同的(请参阅文档了解关联)。具体来说,您将拥有:

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.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'
})

上述代码的导入部分如下所示:

独特:真正的

这将导致:

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

最新更新