Yii2:如何合并为一个关系

时间:2018-05-26 09:06:05

标签: merge yii2 relation

我有两个关系

public function getAnnounceComments()
{
    return $this->hasMany(AnnounceComment::className(), ['user_id' => 'id']);
}


public function getAnnounceRates()
{
    return $this->hasMany(AnnounceRate::className(), ['user_id' => 'id']);
}

如何将用户的两个关系合并为同一个announce_id,我可以这样称呼它 $user->commentAndRate->comment$user->commentAndRate->rate

1 个答案:

答案 0 :(得分:0)

我确实喜欢这样:

将此关系添加到AnnounceComment模型:

public function getRate()
{
    return $this->hasOne(AnnounceRate::className(), ['announce_id' => 'announce_id']);
}

当我打电话时,用户会这样:

$user = User::find()->with('announceComments.rate')->where('id=1')->one()

然后我可以轻松打电话:

foreach ($model->announceComments as $key => $comment) {
    echo $comment->text . $comment->rate->count`
}

我等待更好的答案:)