Найдите все объекты без связанных объектов has_many

Удалить% 20 ​​(пробел) после адреса в ссылке:)

5
задан Tom Lehman 25 April 2009 в 02:37
поделиться

2 ответа

Вы также можете запросить информацию об ассоциации, используя обычный синтаксис поиска:

Order.find(:all, :include => "shipments", :conditions => ["orders.state = ? AND shipments.id IS NULL", "authorized"])
8
ответ дан 18 December 2019 в 06:51
поделиться

One option is to put a shipment_count on Order, where it will be automatically updated with the number of shipments you attach to it. Then you just

Order.all(:conditions => [:state => "authorized", :shipment_count => 0])

Alternatively, you can get your hands dirty with some SQL:

Order.find_by_sql("SELECT * FROM
  (SELECT orders.*, count(shipments) AS shipment_count FROM orders 
    LEFT JOIN shipments ON orders.id = shipments.order_id 
    WHERE orders.status = 'authorized' GROUP BY orders.id) 
  AS order WHERE shipment_count = 0")

Test that prior to using it, as SQL isn't exactly my bag, but I think it's close to right. I got it to work for similar arrangements of objects on my production DB, which is MySQL.

Note that if you don't have an index on orders.status I'd strongly advise it!

What the query does: the subquery grabs all the order counts for all orders which are in authorized status. The outer query filters that list down to only the ones which have shipment counts equal to zero.

There's probably another way you could do it, a little counterintuitively:

"SELECT DISTINCT orders.* FROM orders 
  LEFT JOIN shipments ON orders.id = shipments.order_id
  WHERE orders.status = 'authorized' AND shipments.id IS NULL"

Grab all orders which are authorized and don't have an entry in the shipments table ;)

3
ответ дан 18 December 2019 в 06:51
поделиться
Другие вопросы по тегам:

Похожие вопросы: