I have double nested include / join of tables.
I need to filter first include using second’s includes column
In the end I want to filter users that have no linked items in associated table.
I’m using Sequelize in Nest.js with PostgreSQL
users.findAll({
raw: true,
nest: true,
where: {} //something
include: [
{
model: OneTimeUrlModel,
required: false,
where: {
'$sent_msgs.id$': { [Op.ne]: null },
},
include: [
{
model: SentMsgModel,
attributes: ['id'],
required: false,
},
],
},
],
});
I get this SQL:
SELECT "UserModel"."id", "UserModel"."phone", "urls"."id" AS "urls.id", "urls"."user_id" AS "urls.user_id", "urls->sent_msgs"."id" AS "urls.sent_msgs.id"
FROM "users" AS "UserModel"
LEFT OUTER JOIN "urls" AS "urls" ON "UserModel"."id" = "urls"."user_id" AND "sent_msgs"."id" IS NOT NULL
LEFT OUTER JOIN "sent_msgs" AS "urls->sent_msgs" ON "urls"."id" = "urls->sent_msgs"."url_id";
and an Error:
error: missing FROM-clause entry for table "sent_msgs"
How do I make this work?
It’s not clear from this example, but what I really want is to filter only “bad” urls and pick users without them (users that have urls = null).
So I can’t move “where” above to users.
I also can’t move “where” below to the sent_msgs as filtering depends on type of url as well.