How to do “where exists” in Arel

后端 未结 2 1912
情深已故
情深已故 2020-12-29 07:42

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 *
         


        
相关标签:
2条回答
  • 2020-12-29 07:46

    I think that you can neatly use a counter_cache for this one :

    http://asciicasts.com/episodes/23-counter-cache-column

    0 讨论(0)
  • 2020-12-29 07:54

    Here you go:

    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`))"
    

    Though, an inner join would do this in a more simple - and eventually less performant - way :

    Supplier.joins :orders

    0 讨论(0)
提交回复
热议问题