复杂的mysql加入

时间:2011-05-10 08:38:59

标签: mysql ruby-on-rails ruby-on-rails-3 inner-join

我正在尝试选择一些组织INNER JOINING其他两个模型.. 尝试过很多东西,但我对这些东西还很陌生,而且它不会起作用。

以下是3种型号:

class User < ActiveRecord::Base
  has_one :contact, :as => :contactable
  has_one :organization
  has_one :friend
end

class Contact < ActiveRecord::Base
  belongs_to :contactable, :polymorphic => true
  belongs_to :city
  belongs_to :province
end

class Organization < ActiveRecord::Base
  belongs_to :user
end

这是查询最终应该是什么样的:

SELECT * FROM organizations 
INNER JOIN users ON 
( organizations.`user_id` = users.`id` ) 
INNER JOIN contacts ON 
( contacts.`contactable_id` = users.`id` AND contacts.`contactable_type` = "User" AND contacts.`city_id` = 2340 )

0 个答案:

没有答案