Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use Joins for multiple tables in yii2

I am using yii2, I have 3 tables: posts, fans, comments and i want to use joinWith() to get the posts with their comments and the fan name (in fans table) for post and comments. what i wrote is this query:

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

and I added these two functions for the relations:

<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 posts and the data of the fan who wrote the post and its comments but what i need is the data of fan that wrote the comments also, so how can i join comments with fans table ??

like image 460
ruba Avatar asked Dec 15 '22 23:12

ruba


1 Answers

Make sure you have a fan relation in your Comments model, then you can use the following to get all comments for each post and the fan relation for each comment:

facebook_posts::find()->joinWith('fans')->joinWith(['comments', 'comments.fan'])->all();
like image 120
davey Avatar answered Dec 17 '22 11:12

davey