4

我正在使用 yii2,我有 3 个表:帖子、粉丝、评论,我想使用 joinWith() 来获取帖子及其评论和粉丝名称(在粉丝表中)用于帖子和评论。我写的是这个查询:

<pre>
 facebook_posts::find()->joinwith('fans')->joinWith('comments')->all();
</pre>

我为关系添加了这两个函数:

<pre>
    public function getfans() {
        return $this->hasOne(Fans::className(), ['id' => 'from_id'])->from(fans::tableName() . ' FBF');
    }
    public function getComments() {
        return $this->hasMany(Comments::className(), ['parent_id' => 'id'])->from(comments::tableName() . ' FBC');
    }
</pre>

这给了我帖子和写帖子及其评论的粉丝的数据,但我需要的是写评论的粉丝的数据,那么我如何将评论加入粉丝表?

4

1 回答 1

12

确保您的模型中有一个fan关系Comments,然后您可以使用以下内容获取每个帖子的所有评论以及每个评论的粉丝关系:

facebook_posts::find()->joinWith('fans')->joinWith(['comments', 'comments.fan'])->all();
于 2014-05-20T07:47:16.553 回答