laravel 8中如何写子查询?

How to write sub queries in 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 查询构建器中编写此查询?

如果您的 ORM 模型已定义(并且您同时拥有 PostPostLike 模型),请在您的 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'];
}

Note that above we use post_like alias, and limit to user_id, just to much OP requirements; Else we could simply set likes_count to the number of relations, like:

->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