10/12/2006

自我的 n:m mapping 設定方式

在 Active Record 中
n : m 一向是使用 has_many_and_belongs_to_many 來設定之間的關係
我們必須先有兩個具有 n:m 關係的 table
並且要有一個 mapping table
然後設定其中的關係
但是如果 自己對自己有 n:m 關係怎辦?
舉個最常見到的例子
人有許多朋友,但是朋友也是人呀
也就是說,Person 跟 Person 之間的朋友關係是屬於 n:m
在實做上,要實做兩個 table ,people 還有 friends
  • table people 擁有 id , name , password ..... 之類的 column
  • table friends 是 join table ,只有兩個 column ,person_id 還有 friend_id,都是指回 people 的 foreign key
我們想設定Person 自我的 n:m 關係怎麼辦?

請在 person 這個 model 設定
has_and_belongs_to_many :friends,
:class_name => "Person",
:join_table => "friends",
:association_foreign_key => "friend_id",
:foreign_key => "person_id"

  • :class_name 代表你這個關係是跟 Person 這個 Model 有關係
  • :join_table 代表 mapping table 是 friends 這個 table
  • :association_foreign_key => "friend_id", :foreign_key => "person_id" 就是相關的 foreign key 欄位

當這樣設好後
你就可以使用
a = Person.find(1)
a.friends.each { |i| i.name ..... } # 每個 i 都是 Person model
之類的用法

沒有留言: