andrzej1_1
(Andrzej1 1)
1
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]);
},
]);
Bizley
(Bizley)
2
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).
andrzej1_1
(Andrzej1 1)
3
Your relation is wrong, but currently I solved problem. Besides thanks for showing shorter way to get id.
Bizley
(Bizley)
4
Only if post_id is property of Post.
softark
(Softark)
5
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']);
}