【问题标题】:How to write sub queries in laravel 8?如何在 laravel 8 中编写子查询?
【发布时间】: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


    【解决方案1】:

    如果您的 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'];
    }
    

    注意上面我们使用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

    【讨论】:

    • @InfasMohammed 我刚刚编辑过,答案来自乌鲁丁 ;-)
    猜你喜欢
    • 2017-05-25
    • 2021-03-30
    • 2017-11-28
    • 2019-07-13
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    • 2020-06-15
    相关资源
    最近更新 更多