2013-02-26 145 views
0
rails --version 
2.3.16 
ruby --version 
1.8.7 

型號:如何在RoR ActiveRecord中使用多個JOIN和OR編寫此MYSQL查詢?

class AToB 
    belongs_to :a 
    belongs_to :b 
    default_scope :include => [:a, :b] 
end 
class A 
    has_many :a_to_bs 
    has_many :bs, :through => :a_to_bs 
    named_scope :twos, :conditions => { :var => 2 } 
    named_scope :buzzed, :conditions => { :fizz => ['buzz'] } 
end 
class B 
    has_many :a_to_bs 
    has_many :as, :through => :a_to_bs 
end 

MySQL查詢:

SELECT COUNT(DISTINCT a.id), COUNT(DISTINCT c.id) 
FROM a_to_b 
INNER JOIN a on a.id = a_to_b.a_id 
INNER JOIN b on b.id = a_to_b.b_id 
WHERE (a.var = 2 AND a.fizz in ('buzz') AND 
     (b.foo = TRUE OR b.bar = TRUE OR (b.moo = TRUE AND a_to_b.goo = FALSE)) 
    ) 

也需要這種變化

SELECT COUNT(DISTINCT a.id), COUNT(DISTINCT c.id) 
FROM a_to_b 
INNER JOIN a on a.id = a_to_b.a_id 
INNER JOIN b on b.id = a_to_b.b_id 
WHERE (a.var = 2 AND a.fizz in ('buzz') AND 
     NOT (b.foo = TRUE OR b.bar = TRUE OR (b.moo = TRUE AND a_to_b.goo = FALSE)) 
    ) 

我已經一派無數簡單的例子,讀rails docs等。無濟於事。

回答

0

這有點兒工作:

scope = A.twos.buzzed 
scope.count(:joins => { :b => :a_to_b }, :conditions => "b.foo = TRUE OR b.bar = TRUE OR (b.moo = TRUE AND a_to_b.goo = FALSE)") 

要去考多一點我敢肯定之前。

0

讓我試着回答這個問題。例如你的模型如下Rails中:

#a.rb 
class A < ActiveRecord::Base 
    attr_accessible :var, :fizz 
    has_many :a_to_bs 
end 

#b.rb 
class B < ActiveRecord::Base 
    attr_accessible :foo, :bar, :moo 
    has_many :a_to_bs 
end 

#a_to_b.rb 
class AToB < ActiveRecord::Base 
    attr_accessible :goo, :a_id, :b_id, :a, :b 
    belongs_to :a 
    belongs_to :b 
end 

的第一個典型的查詢是:

records = AToB.where("a.var = ? AND a.fizz in (?) AND (b.foo = ? OR b.bar = ? OR 
      (b.moo = ? AND a_to_b.goo = ?))", 2, 'buzz', true, true, true, false) 

而對於第二個那就是:

records = AToB.where("a.var = ? AND a.fizz in (?) AND NOT (b.foo = ? OR b.bar = ? OR 
     (b.moo = ? AND a_to_b.goo = ?))", 2, 'buzz', true, true, true, false) 

假設你提到的查詢是正確的,答案是正確的。

+0

這不適合我。我添加了一些關於模型設置的信息,包括一些命名範圍。另外,我不能使用'.where()',因爲我沒有使用Rails 3。 – Kache 2013-02-26 11:16:16