简体   繁体   中英

how to combine where and order for SQL query

I have projects and grants that are connected through a match. The grant has an expiration date. I want to sort the matches of a project by the grants expiration date.

This get's me the matches based on expiration date:

def self.expires_date_between(from, to)
  Match.where(:grant_id => Grant.where("expires_at  >= ? and expires_at <= ?", from, to))
end

And this shows the matches based on a specific date range.

def current_matches
  range = user.current_period_range
  matches.expires_date_between(range[0], range[1])
end

This works great to show the grants based on a specific time period but the grants aren't showing in order of date (expires_at). It appears that grants are being sorted by the date they were created instead. How can I change my query so that the grants are listed in order of expiration date?

I tried:

def self.expires_date_between(from, to)
  Match.where(:grant_id => Grant.where("expires_at  >= ? and expires_at <= ?", from, to).order('expires_at asc'))
end

This doesn't throw an error but it also doesn't change the order of the grants. Any ideas?

Assuming you have defined your associations in your models, this should work (but has not been tested):

Match
  .joins(:grant)
  .merge(Grant.where("expires_at  >= ? and expires_at <= ?", from, to))
  .order('expires_at asc')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM