Yii:如何将父对象定义为相关子对象


Yii: How to define parent object to related childs?

2表:线程和注释(例如)=>线程;评论模型

Thread.php

public function relations()
{
    return array(
        'comments'=>array(self::HAS_MANY, 'Comment', 'thread_id'),
    );
}

如何为每个注释子对象定义属性父线程对象?

类似这样的东西:

$model = Thread::model()->with('comments')->findAll();
foreach($model->comments as $comment)
  echo $model->id == $comment->thread->id; // 1

第页。S.对不起,我的英语太差了。

您需要在Comment模型中定义此规则:

public function relations()
{
    return array(
       'thread'=>array(self::BELONGS_TO, 'Thread', 'thread_id'),
    );

}

这意味着每个Comment只属于一个线程。现在,使用这种结构,您可以执行以下操作:

$comments = Comment::model()->with("thread")->findAll();
foreach($comments as $comment)
     ...