在Sequelize.js ORM中,很难弄清楚如何在表和表本身之间创建多对多关系



我的目标是在用户之间创建友谊功能。为此,到目前为止,我正在考虑创建两个表:

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,
allowNull: false
},
password: {
type: DataTypes.STRING,
allowNull: false
},
email: {
type: DataTypes.STRING,
unique: true,
allowNull: false
}
},
{
freezeTableName: true,
timestamps: false
}
);
const Friendship = sequelize.define(
'Friendship',
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false
},
accepted: {
type: DataTypes.BOOLEAN,
allowNull: false
}
},
{
freezeTableName: true,
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
)