SELECT
posts.id,
(select count(*) from post_likes where post_id = 13 and user_id = 12) as post_like
FROM
posts
LIMIT 5
如何在 Laravel 查詢構建器中編寫此查詢?
如果您的 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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句