【问题标题】:Many-to-many self join in rails?多对多自我加入轨道?
【发布时间】:2014-10-19 01:03:05
【问题描述】:

Rails 文档提供了一个nice explanation,说明如何处理只需要 has_many-belongs_to 关系的自联接。在示例中,一名员工(作为经理)可以有许多员工(每个员工都作为下属)。

但是,您如何处理 has_many-has_many 自连接(我听说它被称为双向循环关联)?

例如,当一名员工作为经理可以有很多下属,而作为下属的身份也有有很多经理时,您如何处理?

或者,换句话说,一个用户可以在哪里关注许多用户并被许多用户关注?

【问题讨论】:

标签: ruby-on-rails activerecord


【解决方案1】:

一个用户可以有很多:

  • 作为被关注者的追随者
  • 以追随者的身份追随者。

user.rb 的代码如下所示:

class User < ActiveRecord::Base
  # follower_follows "names" the Follow join table for accessing through the follower association
  has_many :follower_follows, foreign_key: :followee_id, class_name: "Follow" 
  # source: :follower matches with the belong_to :follower identification in the Follow model 
  has_many :followers, through: :follower_follows, source: :follower

  # followee_follows "names" the Follow join table for accessing through the followee association
  has_many :followee_follows, foreign_key: :follower_id, class_name: "Follow"    
  # source: :followee matches with the belong_to :followee identification in the Follow model   
  has_many :followees, through: :followee_follows, source: :followee
end

follow.rb 的代码如下:

class Follow < ActiveRecord::Base
  belongs_to :follower, foreign_key: "follower_id", class_name: "User"
  belongs_to :followee, foreign_key: "followee_id", class_name: "User"
end

最需要注意的可能是user.rb 中的:follower_follows:followee_follows。以磨坊(非循环)关联为例,一个团队可能有多个:players:contracts。这对于 玩家 来说并没有什么不同,他们可能也有很多:teams:contracts(在这样的玩家 的职业生涯中)。

但是在这种情况下,只有一个命名模型存在(即用户),相同地命名 through: 关系(例如through: :follow)将导致不同用例的命名冲突(或访问点)连接表。创建:follower_follows:followee_follows 是为了避免这种命名冲突。

现在,一个用户可以拥有多个:followers:follower_follows和多个:followees:followee_follows

  • 为了确定 User 的 :followees(在对数据库的 @user.followees 调用时),Rails 现在可以查看 class_name 的每个实例:“Follow”,其中此类用户是关注者(即foreign_key: :follower_id)通过:这样的用户的:followee_follows。
  • 为了确定 User 的 :followers(在 @user.followers 调用数据库时),Rails 现在可以查看 class_name 的每个实例:“Follow”,其中此类 User 是被关注者(即foreign_key: :followee_id),通过:这样的用户的:follower_follows。

【讨论】:

  • 这是一个不错的答案,但如果他需要各向同性连接怎么办?
  • 谢谢@MarianTheisen。我不确定我是否理解这个问题。在这种情况下,关注者和关注者是完全独立的用户组。组之间可以有 0 到 100% 的重叠。您是说连接用户的自联接表要求 100% 重叠的情况吗?
  • 对不起,我的意思是说......他谈到了在连接表中不需要额外字段(“单向,没有额外字段”)的场景和你在哪里做( “单向,带有附加字段”)。
  • 这可以与双向情况形成对比,在这种情况下,through: 关联需要以不同于连接模型(即Follow)的方式命名(即through: :followee_followsthrough: :follower_follows) ) 来说明关联的双向性质
  • 查看my blog post以获得更完整的讨论
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-08
  • 2023-03-03
  • 2011-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-18
相关资源
最近更新 更多