ruba ruba - 10 months ago 49
PHP Question

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:


and I added these two functions for the relations:

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

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

Answer Source

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', ''])->all();