3

我有一个奇怪的情况,需要双重内连接。我已经尝试了我需要的查询,我只是不知道如何让 rails 做到这一点。

数据

  • 帐户(has_many :sites)
  • 站点(habtm :users,belongs_to :account)
  • 用户(habtm :sites)

忽略它们是 habtm 或其他什么,我可以使它们 habtm 或 has_many :through。

我希望能够做到

@user.accounts

或者

@account.users

那我当然应该可以

@user.accounts < @some_other_account

然后让@user.sites 包含来自@some_other_account 的所有站点。

我已经摆弄了 habtm 和 has_many :through 但无法让它做我想做的事。

基本上我需要以这样的查询结束(从 phpmyadmin 复制。经过测试并且有效):

SELECT accounts.* 
FROM accounts
INNER JOIN sites ON sites.account_id = accounts.id
INNER JOIN user_sites ON sites.id = user_sites.site_id
WHERE user_sites.user_id = 2

我可以这样做吗?进行这种双重连接是个好主意吗?我假设如果用户一开始就与帐户建立关联,然后担心得到@user.sites,它会更好地工作,但如果保持原样(用户<->网站)。

4

2 回答 2

3

我认为最好为此创建自定义方法,而不是试图将其硬塞进一个关联中。例如。

# in user.rb
def accounts
  Account.all(:include => {:sites => :users}, :conditions => ["users.id=?", self])
end

def add_account(other_account)
  other_account.sites.each do |site|
    self.sites << site
  end
end

# in account.rb
def users
  User.all(:include => {:sites => :account}, :conditions => ["accounts.id=?", self])
end

未经测试,但这应该适用于 HABTM 或has_many :through关联。根据您采用的方法,您可以对查询进行一些优化。

有一天,我们可能会得到对深度嵌套的支持,has_many :through它可以处理其中的一些问题。

于 2009-07-31T22:39:50.247 回答
2

这可能对您有用(Rails 2.x)

http://github.com/ianwhite/nested_has_many_through

于 2010-04-22T05:10:14.037 回答