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'),
    );
}

如何为每个评论子对象定义 属性 父 Thread 对象?

像这样:

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

P.S。对不起我的英语,我知道它很糟糕。

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

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

}

这意味着每条评论只属于一个话题。 现在,使用此结构,您可以执行以下操作:

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