我在MySQL数据库上使用sequelize。我将一个表上的所有记录同时与另一张表连接在一起。如果连接表上的WHERE
条件不满足,我试图不包括结果。在WHERE
子句中,我试图将主表中的值与联接表进行比较,但它不起作用:
const expiredMemberships = await Membership.findAll({
include: [
{
model: User,
attributes: ['id'],
include: [
{
model: Post,
required: true,
attributes: ['id', 'created'],
where: {
created: {
[Op.gt]: '$Membership.created$',
},
},
},
],
},
],
attributes: ['id', 'created'],
where: {
isActive: true,
},
});
它创建以下查询:
SELECT `Membership`.`id`,
`Membership`.`created`,
`user`.`id` AS `user.id`,
`user->posts`.`id` AS `user.posts.id`,
`user->posts`.`created` AS `user.posts.created`
FROM `membership` AS `Membership`
LEFT OUTER JOIN ( `user` AS `user` INNER JOIN `post` AS `user->posts`
ON `user`.`id` = `user->posts`.`user_id`
AND `user->posts`.`created` > 'Invalid date' )
ON `Membership`.`user_id` = `user`.`id`
AND (`user`.`deleted` = '9999-12-31 23:59:59')
WHERE `Membership`.`is_active` = true;
您可以看到它显示'$Membership.created$'
为Invalid date
。在where子句中使用联接表的列值的正确方法是什么?
答案 0 :(得分:0)
您可以使用以下方式对成员资格表的创建字段使用别名: membership_created
const expiredMemberships = await Membership.findAll({
include: [
{
model: User,
attributes: ['id'],
include: [
{
model: Post,
required: true,
attributes: ['id', 'created'],
where: {
created: {
[Op.gt]: 'membership_created',
},
},
},
],
},
],
attributes: ['id', ['created', 'membership_created']],
where: {
isActive: true,
},
});