[英]Rails: select model
我有一個模特Shop
:
class Shop < ActiveRecord::Base
has_and_belongs_to_many :services
end
和模型Service
:
class Service < ActiveRecord::Base
has_and_belongs_to_many :shops
end
我想查詢所有提供以下所有服務的商店:
因此,請退還所有包含服務reparation AND advise AND shipping
商店,並提供reparation AND advise AND shipping
。
僅通過ActiveRecord查詢可以做到這一點嗎?
謝謝!
請參閱MySQL:選擇聯接表匹配所有值的記錄,以了解如何在sql中進行操作。
對於一個更簡單的方法,它執行一系列簡單查詢而不是單個復雜查詢,您可以執行以下操作:
#starting with the services in an array called @services
#(which could come from params[:service_ids] for example)
#find shops which have ALL these services.
shop_ids = @services.map(&:shop_ids).inject{|a,b| a & b}
@shops = Shop.find(shop_ids)
關鍵是.inject{|a,b| a & b}
.inject{|a,b| a & b}
:inject是一種數組方法,該方法在第一個元素和第二個元素(a和b)之間執行功能,然后再次將該結果與塊一起使用,與第三個元素等一起使用,遍歷數組。 &
運算符是數組相交的,因此最終只會得到為所有服務返回的shop_id。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.