[英]Sequelize join two columns of one table to the same column of another table
我有一个包含userId1和userId2列的关系表,它基本上存储了两个用户之间的关系, userId1和userId2是这里从用户表 id (PK) 列引用的外键。
id: {
type: DataTypes.INTEGER.UNSIGNED,
autoIncrement: true,
primaryKey: true,
allowNull: false,
},
userId1: {
type: DataTypes.INTEGER.UNSIGNED,
allowNull: false,
},
userId2: {
type: DataTypes.INTEGER.UNSIGNED,
allowNull: false,
},
status: {
type: DataTypes.ENUM,
},
然后是另一个表Posts ,其中包含有关帖子的信息。
id: {
type: DataTypes.INTEGER.UNSIGNED,
autoIncrement: true,
primaryKey: true,
allowNull: false,
},
content: {
type: DataTypes.TEXT,
allowNull: false,
},
postedBy: {
type: DataTypes.INTEGER.UNSIGNED,
allowNull: false,
},
我想获取那些与我有关系的用户(如朋友)的帖子列表,这意味着我的 id 假设为1 ,它在userId1列中,并且 userId2 列中有id ,然后我想获取所有有价值的帖子2来自postedBy栏的帖子。 这种情况可以反之亦然,因为我的 id 可以在userId2列中,我需要获取值在userId1列中的用户的所有帖子。
我已经阅读了所有问题和答案,例如多个关联,但这对我不起作用。
这是我在帖子model 中的关联
Posts.hasOne(RelationModel, {
foreignKey: 'userId1',
sourceKey: 'postedBy',
as: 'first',
})
Posts.hasOne(RelationModel, {
foreignKey: 'userId2',
sourceKey: 'postedBy',
as: 'second',
})
下面是我的包含数组。
include:[
{
model: RelationModel,
as: 'first',
where: {
status: 'accepted',
[Op.or]: [
{ userId1: request.user.id },
{ userId2: request.user.id },
],
},
},
{
model: RelationModel,
as: 'second',
where: {
status: 'accepted',
[Op.or]: [
{ userId1: request.user.id },
{ userId2: request.user.id },
],
},
}
]
从中生成的查询如下,其中151是登录的用户 id,表示我的 id
SELECT
`posts`.*,
`first`.*,
`second`.*
FROM
`posts` AS `posts`
INNER JOIN
`relations` AS `first` ON `posts`.`postedBy` = `first`.`userId1`
AND (`first`.`userId1` = 151
OR `first`.`userId2` = 151)
AND `first`.`status` = 'accepted'
INNER JOIN
`relations` AS `second` ON `posts`.`postedBy` = `second`.`userId2`
AND (`second`.`userId1` = 151
OR `second`.`userId2` = 151)
AND `second`.`status` = 'accepted'
WHERE
`posts`.`deletedAt` IS NULL
ORDER BY `posts`.`id` ASC , `posts`.`id` ASC;
但我要构建的查询如下
SELECT
`posts`.*,
`first`.*
FROM
`posts` AS `posts`
INNER JOIN
`relations` AS `first` ON (`posts`.`postedBy` = `first`.`userId2`
OR `posts`.`postedBy` = `first`.`userId1`)
AND (`first`.`userId1` = 151
OR `first`.`userId2` = 151)
AND `first`.`isFriend` = TRUE
AND `first`.`status` = 'accepted'
WHERE
`posts`.`deletedAt` IS NULL
ORDER BY `posts`.`id` ASC , `posts`.`id` ASC;
如何在 sequelize 中构造这个查询?
您需要为关联中的每个关系以及查询的include
指定一个唯一as
关键字。
Posts.hasOne(RelationModel, {
foreignKey: 'userId1',
sourceKey: 'postedBy',
as: 'first',
});
Posts.hasOne(RelationModel, {
foreignKey: 'userId2',
sourceKey: 'postedBy',
as: 'second',
});
然后,当您查询时,您指定唯一性as
它标识了连接的关系
Post.findByPk(id, {
include: [{
model: RelationModel,
as: 'first',
},
{
model: RelationModel,
as: 'second',
}],
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.