Node.js Sequelize的OneToOne和OneToMany为什么相同?

huangapple go评论65阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年4月11日 03:28:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75980093.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定