[英]Querying with model associations in ruby on rails
模型A has_many模型B。我想返回某些模型B的所有模型As。
例如,我要返回所有擁有福特類型的車輛和雪佛蘭類型的車輛的用戶(福特和雪佛蘭是Vehicle模型的屬性)
我可以輕松查詢以找到所有擁有福特汽車的用戶或所有擁有雪佛蘭汽車的用戶,但是我不想進行2次查詢然后將結果相交。 相反,我只想執行1個查詢。 如何將其合並為1個查詢?
解決方案1
User.joins([:vehicles, :vehicles]).
where("vehicles.model = ? AND vehicles_users.model = ?", "Ford", "Chevy")
解決方案2
支持任意模型。
models = ["Ford", "Chevy"]
User.where(:id => User.joins(:select => "users.id", :vehicles).
where(:vehicles => {:model => models}).group("users.id").
having("COUNT(*) = #{models.size}").limit(30)
)
解決方案3
較慢的解決方案,以防萬一。
User.where([
"EXISTS (
SELECT A.*
FROM vehicles A
WHERE A.user_id = users.id AND
A.model = ?) AND
EXISTS (
SELECT B.*
FROM vehicles B
WHERE B.user_id = users.id AND
B.model = ?)
", "Ford", "Chevy"
])
編輯:要獲得同時使用福特和雪佛蘭汽車的用戶,可以執行以下操作:
User.
select("DISTINCT users.*").
joins("INNER JOIN vehicles AS v1 ON v1.user_id = users.id").
joins("INNER JOIN vehicles AS v2 ON v2.user_id = users.id").
where("v1.type" => "Ford", "v2.type" => "Chevrolet").
編輯2:或者,如果您更喜歡干凈的代碼並且可以容忍2個查詢:
class User < ActiveRecord::Base
scope :with_vehicule, lambda { |type| joins(:vehicles).where(:type => type) }
# ...
end
users_with_both = User.with_vehicle("Ford").to_a & User.with_vehicle("Chevrolet").to_a
舊答案 (檢索具有兩種類型之一的用戶):
User.joins(:vehicle).where(:vehicles => {:type => ["Ford", "Chevrolet"]})
或者(我不確定您的問題中的“屬性”是什么意思):
User.joins(:vehicle).where("vehicles.ford = 1 OR vehicles.chevrolet = 1")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.