本文介绍了如何做“在哪里存在”在Arel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Arel中执行包含where exists的查询?例如,在这样的查询上显示具有至少一个订单的所有供应商:

How do you do a query that includes a "where exists" in Arel? For example on a query like this to show all the suppliers with at least one order:

SELECT *
FROM suppliers
WHERE EXISTS
  (SELECT *
    FROM orders
    WHERE suppliers.supplier_id = orders.supplier_id);

我在Arel文档中看到exists但我是

I see "exists" in the Arel docs http://rubydoc.info/gems/arel/2.0.7/Arel/Nodes/Exists but I'm having trouble using it.

推荐答案

这里:

suppliers= Supplier.arel_table
orders= Order.arel_table
suppliers_with_orders = Supplier.where(
                          Order.where(orders[:supplier_id]
                                        .eq(suppliers[:id])).exists).to_sql =>
"SELECT `suppliers`.* FROM `suppliers` 
 WHERE (EXISTS (SELECT `orders`.* 
                FROM `orders` 
                WHERE `suppliers`.`id` = `orders`.`supplier_id`))"

这篇关于如何做“在哪里存在”在Arel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 19:37