【发布时间】:2022-01-03 15:54:10
【问题描述】:
SELECT
posts.id,
(select count(*) from post_likes where post_id = 13 and user_id = 12) as post_like
FROM
posts
LIMIT 5
如何在 Laravel 查询构建器中编写此查询?
【问题讨论】:
标签: php mysql laravel laravel-8
SELECT
posts.id,
(select count(*) from post_likes where post_id = 13 and user_id = 12) as post_like
FROM
posts
LIMIT 5
如何在 Laravel 查询构建器中编写此查询?
【问题讨论】:
标签: php mysql laravel laravel-8
如果您的 ORM 模型已定义(并且您同时拥有 Post 和 PostLike 模型),请在您的 Post.php 模型中创建关系(如果尚未),例如:
public function likes(){
return $this->hasMany(PostLike::class);
}
然后,如果您只需要计数,请尝试以下操作:
$userId = 12;
$postList = Post::query()
->whereId(13)
->withCount(['likes', 'likes AS post_like' => function ($query) use($userId) {
$query->where('user_id', '=', $userId);
}])
->limit(5)
->get();
// Then do something with result.
foreach ($postList as $post) {
$count = $post['post_like'];
}
注意上面我们使用
post_like这个别名,并且限制为user_id,只是对OP的要求比较高;否则我们可以简单地将likes_count设置为关系的数量,例如:->withCount('likes')
但是您可以使用 whereHas(...) eloquent 方法对子查询使用关系,例如:
Post::query()->whereHas('likes', function($query){
$query->where(...your statements for sub query go there);
}, '>', 4)->limit(5)->get(); //Select where more than 4 relation found with given parameters
更多信息请见:https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence
【讨论】: