英文:
Why Nodejs sequelize OneToOne same as OneToMany?
问题
我已经创建了两个表,它们具有一对一的关系
父表 "user" 和子表 "userinfo"
但是,我可以创建任意数量的具有相同外键的子项,它不会报错
我应该怎么做才能阻止它
这是我尝试过的内容:
models/index.js
//...配置
db.users = require("./Users")(sequelize, DataTypes);
db.userinfo = require("./UserInfo")(sequelize, DataTypes);
db.users.hasOne(db.userinfo);
db.userinfo.belongsTo(db.users, {
foreignKey: {
name: "userId",
type: DataTypes.UUID,
},
});
英文:
I have Created Two tables That has OneToOne relationship
Parent Table "user" and child table "userinfo"
but I can create as many childs I want that has the same foreignKeys,it doesnt respond any error
What should i do to stop it
here is what i haave tried:
models/index.js
//...configs
db.users = require("./Users")(sequelize, DataTypes);
db.userinfo = require("./UserInfo")(sequelize, DataTypes);
db.users.hasOne(db.userinfo);
db.userinfo.belongsTo(db.users, {
foreignKey: {
name: "userId",
type: DataTypes.UUID,
},
});
答案1
得分: 1
尽管您已设置外键,但您还需要强制执行唯一约束。要在userinfo
表的userId
外键上强制执行唯一约束,请执行以下操作:
db.users.hasOne(db.userinfo);
db.userinfo.belongsTo(db.users, {
foreignKey: {
name: "userId",
type: DataTypes.UUID,
unique: true // 强制唯一约束
}
});
通过设置unique: true
,您确保“user”表中的每个用户只能有一个关联记录。
英文:
Although you've set up a foreign key, you need to also enforce unique constraints. To enforce a unique constraint on the userId
foreign key in the userinfo
table, do this:
db.users.hasOne(db.userinfo);
db.userinfo.belongsTo(db.users, {
foreignKey: {
name: "userId",
type: DataTypes.UUID,
unique: true // enforce unique constraint
}
});
By setting unique: true
, you ensure that each user in the "user" table can only have one associated record.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论