Kohana 3.1 ORM:加入has_many

时间:2011-06-10 15:13:03

标签: kohana-3 kohana-orm

我有用户,消息和评论。

用户ID user_id

消息id user_id

评论ID message_id

我可以使用with()获取用户的消息数据。

$model = ORM::factory('message');
$messages = $model
            ->with('user')
            ->find_all();

with('comment')不起作用。我猜是因为它是为一对一的关系创建的,而我有留言has_many评论。

如何将评论数据添加到$ message中?如下所示:['message_id'] ['comment_id'] [DATA]?

1 个答案:

答案 0 :(得分:1)

<强> 0。定义关系:

用户has_many消息 留言has_many评论 消息belongs_to用户 评论belongs_to消息

class Model_User extends ORM {
    protected $_has_many = array('messages' => array());
}

class Model_Message extends ORM {
    protected $_belongs_to = array('user' => array());
    protected $_has_many = array('comments' => array());
}

class Model_Comment extends ORM {
    protected $_belongs_to = array('message' => array());
}

<强> 1。获取用户消息:

$messages = ORM::factory('user', $user_id)->messages->find_all();
foreach($messages as $message) {...}

<强> 2。获取邮件所有者:

$user = ORM::factory('message', $message_id)->user; // without find_all()!

第3。获取消息评论:

$comments = ORM::factory('message', $message_id)->comments->find_all();
foreach($comments as $comment) {...}