【问题标题】:Rails left join conditionalRails 左连接条件
【发布时间】:2016-05-04 13:41:44
【问题描述】:

我不知道编写 activerecord 查询以选择必要数据的好方法。 我有 Customer 表,里面有很多项目

Customers(id)

item表,属于客户(一个客户可以有一个item,那么这个item可以属于另一个客户,所以customer_id就是当前客户)

Items(id, price, customer_id)

订单项(连接表:项目多对多订单)

LineItems(id, item_id, order_id, price, quantity)

通过 line_items 订购 has_many 项。

Orders(id, total, status, customer_id)

嗯,我想获取所有项目,不包括在没有状态 1、2、3 的订单中(状态是一个整数字段)

所以我需要加入客户和项目,然后通过 line_items 表离开加入有条件的订单(不包括状态...)。如何通过 ActiveRecord 实现它。或 SQL。顺便说一句:我使用 psql。 谢谢。

问题是,我想获取所有不包含在没有状态 1、2、3(状态是整数字段)的订单中的项目

【问题讨论】:

  • Customer.joins(:items).includes(items: :orders).where.not(orders: {status: [1, 2, 3]})
  • 但似乎我应该将 where 子句添加到左外连接
  • 你能帮我写一个原始的 sql 查询吗?

标签: sql ruby-on-rails postgresql join activerecord


【解决方案1】:

试试这个:

Item.includes(:orders).where.not(orders: {status: [1,2,3]})

您可以使用to_sql检查生成的SQL

编辑

要包含items,其中确实有order

Item.includes(:orders).where("orders.status NOT IN(?) OR line_items.item_id IS NULL",[1,2,3])

【讨论】:

  • 首先,有商品,没有订单。
  • 结果应该包括没有任何订单的商品。因此,一个项目可以有状态为 0 或 4 的订单,或者一个项目不能有任何订单。我只想排除订单状态为 1、2、3 的商品
  • @AndreyMoroz 我添加了一个EDIT,试试看吧..我还没有测试过。
  • 我想通过客户来做,所以我想像 Customer.active 一样过滤它们.....
  • 看起来不错,但我需要将项目加入活跃客户。客户有 id,状态,我应该得到具有活跃状态的客户的项目
猜你喜欢
  • 2015-07-18
  • 2015-05-13
  • 1970-01-01
  • 1970-01-01
  • 2011-12-11
  • 2012-02-27
  • 2013-01-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多