如何解决无法在Sequelize.js ORM中弄清楚如何在表与其自身之间创建多对多关系 我可以随意使用您提供的信息自行定义表:我认为以下代码可以解决您的问题:这些定义将在postgreSQL中生成以下内容仅显示Friendship表:
我的目标是在用户之间创建友谊功能。为此,到目前为止,我正在考虑创建2个表:
Table: Users
Columns: id,username,password,email
和
Table: Friendships
Columns: id,userId1,userId2,accepted
我正在考虑通过联结表友谊在用户表与其自身之间建立多对多关系。友谊表将包含两个用户的userId和一个接受的布尔值,它表示友谊是已接受还是未决。友谊总是两面的,如果用户A是与用户B的朋友,则意味着用户B也是与用户A的朋友
问题在于,表Users与自身之间的多对多关系使我有些困惑。在Sequelize.js中,当我建立多对多关系时,我会这样做:
User.belongsToMany(Server,{ through: ServerUser })
Server.belongsToMany(User,{ through: ServerUser })
我声明用户可以属于许多服务器,并且该服务器可以属于许多用户。此关系通过ServerUser表链接。
现在考虑到我正在尝试在用户表与其本身之间建立多对多关系,如果我遵循相同的路线,则必须执行以下操作:
User.belongsToMany(User,{ through: Friendship })
User.belongsToMany(User,{ through: Friendship })
这对我来说毫无意义。我可以尝试哪种方法?
解决方法
我可以随意使用您提供的信息自行定义表:
Table: Users Columns: id,username,password,email
和
Table: Friendships Columns: id,userId1,userId2,accepted
我认为以下代码可以解决您的问题:
const User = sequelize.define(
'User',{
id: {
type: DataTypes.INTEGER,primaryKey: true,autoIncrement: true,allowNull: false
},username: {
type: DataTypes.STRING,password: {
type: DataTypes.STRING,email: {
type: DataTypes.STRING,unique: true,allowNull: false
}
},{
freezeTableName: true,timestamps: false
}
);
const Friendship = sequelize.define(
'Friendship',accepted: {
type: DataTypes.BOOLEAN,timestamps: false
}
);
Friendship.belongsTo(User,{
foreignKey: 'userId1',unique: false
});
Friendship.belongsTo(User,{
foreignKey: 'userId2',unique: false
});
这些定义将在postgreSQL
中生成以下内容(仅显示Friendship
表):
CREATE TABLE public."Friendship"
(
id integer NOT NULL DEFAULT nextval('"Friendship_id_seq"'::regclass),accepted boolean NOT NULL,"userId1" integer,"userId2" integer,CONSTRAINT "Friendship_pkey" PRIMARY KEY (id),CONSTRAINT "Friendship_userId1_fkey" FOREIGN KEY ("userId1")
REFERENCES public."User" (id) MATCH SIMPLE
ON UPDATE CASCADE
ON DELETE SET NULL,CONSTRAINT "Friendship_userId2_fkey" FOREIGN KEY ("userId2")
REFERENCES public."User" (id) MATCH SIMPLE
ON UPDATE CASCADE
ON DELETE SET NULL
)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。