关于 ruby?? on rails:复杂的 SQL postgres 查询到 ActiveRecord 表示法?

Complex SQL postgres query into ActiveRecord notation?

希望 ActiveRecord 向导可以帮助我确定这种查询是否可以使用 AR 语句完成,即无需执行原始 SQL 或深入 Arel?

我接近了,但似乎无法弄清楚如何添加子查询。我在 Rails 5.1.1 上。

1
2
3
4
5
6
SELECT s.id AS stock_id, s.count, adjustments.count AS
adjustment_count, adjustments.reason AS adjustment_reason
FROM
(SELECT * FROM stocks WHERE inventory_id = 6) AS s
LEFT JOIN adjustments
ON (s.id = adjustments.stock_id AND adjustments.reason='run_use')

最终结果应该是所有库存 id 为 6 的库存,额外的列显示对它们进行的调整(如果存在)。

如果我在 Navicat 中运行 RAW SQL,我会得到这个结果,这就是我试图通过 ActiveRecord 得到的结果:enter

1
2
3
Stock.where(inventory:6)
.left_joins(:adjustments)
.where("adjustments.reason = 'run_use'")


其中一个应该适合你:

1
2
Stock.eager_load(:adjustments)
  .where("adjustments.reason = ? OR stocks.inventory_id = ?","run_use", 6)

1
2
Stock.eager_load(:adjustments)
  .where(adjustments: { reason:"run_use" }, inventory_id = 6)


嗯。看来您是想说:

Give me all Stock that belong to Inventory with id = 6 that also have Adjustments with a reason of 'run use'.

怎么样:

1
2
3
4
Stock.
  WHERE(inventory_id: 6).
  joins(:adjustments).
  WHERE(adjustments: { reason: 'run_use' })

来自指南