September 5,2006

同一組 DB table ,不同關係的設定方式

應該很多人有類似的想法吧?
今天兩個 tables ,他們的關聯不只一種

舉個例子:
User 這個 table 跟 Email 這個 table 是 1:m 的關係
email 這個欄位有 user_id -> 代表這個信的收信人是誰
還有 sender_user_id -> 代表這個信的寄件人是誰
今天如果使用 ActiveReocrd 的預設方式





class User < ActiveRecord::Base
has_many :emails
end

class Email < ActiveRecord::Base
belongs_to :user
end


這樣只能使用 User.emails 代表這個人有多少信件要收
但是如果我們也想用 ActiveRecord 做到 User.send_emails 這樣
代表這個人有多少信件要寄呢?

我們可以使用 Virtual Table 來解決




class User < ActiveRecord::Base
has_many :messages
has_many :send_messages , :foreign_key => 'sender_id'
end

class Message < ActiveRecord::Base
belongs_to :user
end

class SendMessage < Message
belongs_to :user , :foreign_key => 'sender_id'
end


如此就可以直接使用

User.messages還有User.send_messages


Posted by thegiive at 樂多Roodo! │08:06 │回應(1)引用(0)Ruby and Rails
樂多分類:網路/3C 工具:編輯本文
Ads by Roodo! 

引用URL

http://cgi.blog.roodo.com/trackback/2106403
回應文章
真有趣的方法,不知道這種作法在CakePHP能不能用,晚點來試試看好了..^_^..
Posted by ㄚ凱 at September 5,2006 11:43