双加入habtm在Email
-
05-07-2019 - |
题
我有一个奇怪的情况涉及的需要一双内加入。我已经尝试了查询,我需要,我只是不知道怎么做轨做。
该数据
- 帐户(has_many:网站)
- 网站(habtm:用户,belongs_to:账户)
- 用户(habtm:网站)
忽略他们habtm或什么的,我可以让他们habtm或has_many:通过。
我希望能够做到的
@user.accounts
或
@account.users
然后当然,我应该能做到
@user.accounts < @some_other_account
然后有@户。网站包括所有网站自@some_other_account.
我已经摆弄habtm和has_many:通过,但不能让它来做什么我想要的。
基本上我需要结束了一个查询这样(复制从头文件.测试和工作):
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
我可以这样做?它甚至有一个好主意,要有这种双加入吗?我假设它能更好地工作,如果用户有关联的帐户的开始,然后担心@户。地点相反,但是它的工作更好地为许多其他的事情如果这是保持它的方式是(用户 <->站点)。
解决方案
我认为这是最好的创造定义方法,而不是试图鞋喇叭它变成一个协会。例如。
# 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
这将处理一些这样的。
其他提示
这可能会对你有用(2轨.x)
不隶属于 StackOverflow