1

有没有办法使用 :joins 或 :includes 查询项目,但也可以在同一个查询中返回没有对应关系的结果?

当前示例查询

Company.find(1).users.includes(:billing_statuses).where('billing_statuses.expires < ?', Time.now)

这应该返回所有已过期 billing_statuses 的用户,但是,最终目标是获取所有“未计费”用户,这将包括尚未具有 :billing_statuses 关系的用户。

有没有办法将它组合在一个查询中?

我探索的另一种方法是获取公司的所有用户,然后减去没有过期账单的用户。但我觉得这不是最优化的解决方案。

谢谢!

4

1 回答 1

1

试试这个:

User.where(company_id: 1).joins("LEFT OUTER JOIN billing_statuses ON billing_statuses.user_id = users.id").where("billing_statuses.expires < ? or billing_statuses.id IS NULL", Time.now)

于 2012-05-29T04:59:26.337 回答