question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Using raw sql query in scope

See original GitHub issue

This 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:open
  • Created 6 years ago
  • Reactions:9
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

4reactions
bradisbellcommented, May 16, 2019

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

2reactions
papbcommented, Aug 21, 2019

@bradisbell Stale bot was disabled some time ago 😃

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to write a raw sql in rails scope? - Stack Overflow
The right way would be to use the following: scope :abc, ->(start_date, end_date) { where("created_at >= ? AND created_at <= ?
Read more >
How to make a scope with a raw SQL query? - Laracasts
Hi guys, So I am trying to make a scope with this SQL query: SELECT * FROM ro_container_events WHERE (container_id, location_timestamp, id) IN...
Read more >
Using ActiveRecord Scope Methods in Rails: How and Why
Scope methods in Rails are special class methods enabled by the ActiveRecord query interface, which allows the programmer to write SQL ...
Read more >
How to write a raw sql in rails scope?-mysql - appsloveworld
When I am executing the above scope with the following command it returns blank array. Above command generates the proper sql which I...
Read more >
Rails: Dynamically Chain Scopes to Clean up SQL Queries
As applications become more complicated, retrieving the required information can become a hassle as you dip into utilizing SQL queries. This ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found