SELECT
posts.id,
(select count(*) from post_likes where post_id = 13 and user_id = 12) as post_like
FROM
posts
LIMIT 5
如何在 Laravel 查詢構建器中撰寫此查詢?
uj5u.com熱心網友回復:
如果您的 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/365694.html
