加入后小于/大于的 Where 子句 [英] Where Clause with Less/Greater than after a Join
问题描述
我正在尝试将 joins
与 where
子句结合起来,但是 where
子句不是测试相等性,而是测试大于或等于.
I'm trying to combine a joins
with a where
clause but the where
clause is not testing an equality, it is testing for greater than or equal.
我知道在标准 where 子句中,我可以这样做:
I know in a standard where clause, I can just do this:
Group.where("vote_deadline_at <= ?", Time.now)
查找投票截止日期在未来的所有组.
to find all groups whose vote deadline is in the future.
但是,如果这是在 joins
之后出现的,像这样:
However, what if this comes after a joins
, like this:
User.likes.where(liked_type: "Post").joins("INNER JOIN posts ON posts.id = liked_id").where(posts: {context_type:"Group"}).joins("INNER JOIN groups ON groups.id = posts.context_id").where(groups: {"vote_deadline_at <= ?",Time.now})
直到最后的 where(groups: {"vote_deadline_at <= ?",Time.now})
子句工作正常.它返回一个包含 186 行的 ActiveRecord 集合.但是,当我添加最后的 where
子句时,出现错误:
Everything up to the final where(groups: {"vote_deadline_at <= ?",Time.now})
clause works fine. It returns an ActiveRecord collection of 186 rows. However, when I add the final where
clause, I get the error:
SyntaxError: unexpected '}', expecting end-of-input
...ote_deadline_at <= ?",Time.now})
有什么方法可以使用 where 子句进一步过滤我的结果,该子句仅选择 groups.vote_deadline_at
未来(即小于或等于 Time.now)的行?
Is there any way to further filter my results with a where clause that selects only rows where groups.vote_deadline_at
is in the future (i.e. less than or equal to Time.now)?
推荐答案
我以为我以前试过这个,但显然这个语法有效:
I thought I had tried this before, but apparently this syntax works:
u.likes.where(liked_type: "Post").joins("INNER JOIN posts ON posts.id = liked_id").where(posts: {context_type:"Group"}).joins("INNER JOIN groups ON groups.id = posts.context_id").where("groups.vote_deadline_at <= ?",Time.now)
我得到了完全符合预期的结果.
I got exactly the results I expected.
这篇关于加入后小于/大于的 Where 子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!