Use Joins for multiple tables in yii2

I use yii2, I have 3 tables: posts, fans, comments, and I want to use joinWith () to receive posts with their comments and the fan name (in the fans table) for posts and comments. I wrote this query:

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

and I added these two functions for the relationship:

<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>

this gives me the messages and data of the fan who wrote the message and his comments, but I need the data of the fans who also wrote comments, so how can I join the comments using the fans table?

+3
source share
1 answer

, fan Comments, , :

facebook_posts::find()->joinWith('fans')->joinWith(['comments', 'comments.fan'])->all();
+13

Source: https://habr.com/ru/post/1623077/


All Articles