Optimization of checking whether user liked post [SOLVED]

Hello. After getting posts I am doing query for each to determine user like it or not. I was trying to reduce numbers of queries and do it in one:


$query = Post::find();

$query->joinWith([

   'likes' => function ($query) { 

      $query->andWhere(['user_id' => \Yii::$app->user->identity->id]);

   },

]); 

$posts = $query->all();

but in effect I got only liked posts, not all with certain NULLs.

Database structure:


User: id

Post: id

Like: user_id, post_id

Post model relation:


public function getLikes()

{

   return $this->hasMany(Post::className(), ['post_id' => 'id']);

}

What I did wrong with creating query?

Solved:


$query->joinWith([

   'likes' => function ($query) { 

      $query->onCondition(['user_id' => \Yii::$app->user->identity->id]);

   },

]);

Other way around:




public function getLikes()

{

   return $this->hasMany(Post::className(), ['id' => 'post_id']);

}



And you can write Yii::$app->user->identity->id shorter like Yii::$app->user->id (at least with default User component).

Your relation is wrong, but currently I solved problem. Besides thanks for showing shorter way to get id.

Only if post_id is property of Post.

A Post can have many Likes, not many Posts.




/* Post.php */

public function getLikes()

{

   /* return $this->hasMany(Post::className(), ['post_id' => 'id']); */

   return $this->hasMany(Like::className(), ['post_id' => 'id']);

}