Using raw sql query in scope
See original GitHub issueThis is probably a feature request because I failed to find a way to do it currently.
What I want is being able to pass raw sql to Model.addScope so that query is used as subquery when performing include join.
First thing you are probably gonna ask is why would I want to do that, so here’s my use case (which I think should be too common to not have easy solution by now but somehow I failed to come up with one).
I have two tables, projects and projectStatusChanges
projects:
id | name
---+----------
1 | cool project
projectStatusChanges:
id | projectId | status | createdAt
---+-----------+-----------+----------
1 | 1 | doing | 01-01-2000
2 | 1 | done | 02-01-2000
I need to find all complete projects (the ones where latest projectStatusChange.status is ‘done’). Project.hasOne(ProjectStatusChange) association isn’t doing the trick because, as far as I know, I have no control over which row is picked. So what I wish I would be able to do is something like:
ProjectStatusChange.addScope(
'latest',
`
SELECT "projectId", "createdAt", "status"
FROM
(
SELECT "projectId" AS "_projectId",
MAX ("createdAt") AS "maxCreatedAt"
FROM "projectStatusChanges"
GROUP BY "projectId"
) AS "latestStatusChanges"
JOIN "projectStatusChanges"
ON "latestStatusChanges"."maxCreatedAt" = "projectStatusChanges"."createdAt";
`,
{
raw: true,
},
);
Project.hasOne(ProjectStatusChange.scope('latest'), {
foreignKey: 'projectId',
as: 'currentStatus',
});
If this already have been implemented in some way or if there is better solution for my use case, I hope you can direct me towards it.
Issue Analytics
- State:
- Created 6 years ago
- Reactions:9
- Comments:5 (3 by maintainers)
Stalebot is the worst. There are a ton of useful posts and feature requests on the Sequelize issue tracker, and seemingly all of them have been closed by stalebot. There are also a ton of comments like, “stop posting to +1 something”. I don’t know what folks are supposed to do otherwise, to prevent stalebot from killing off perfectly good discussions and feature requests. So, this is my post here.
+1
@bradisbell Stale bot was disabled some time ago 😃