【问题标题】:Laravel Pagination not working if query contain HAVING statement如果查询包含 HAVING 语句,Laravel 分页不起作用
【发布时间】:2018-09-11 21:40:04
【问题描述】:

Laravel having子句的分页查询问题,请看下面的查询

$data = DB::table('jobs as j')
    ->selectRaw('j.*, (case
        when (seeker_action = 'like' and employer_action = 'like') then 'match'
        when (seeker_action is null and employer_action = 'like') then 'employer-liking'
        when (seeker_action = 'like' and employer_action = 'delete') then 'rejected'
        else seeker_action end) as 'action'')
    ->join('profiles_jobs as p', 'p.job_id', '=', 'j.id')
    ->where('p.profile_id', '=', 2)
    ->whereRaw('(p.seeker_action is not null) or (p.seeker_action is null and p.employer_action = 'like')
        and j.deleted_at is null')
    ->having('action', 'employer-liking');

$data = $data->paginate(10);

我收到的错误如下:

未找到列:1054 '有子句'中的未知列 'action' (SQL: select count(*) as aggregate from jobs as j 内连接 profile_jobs as p on p.job_id = j.id 其中 p.profile_id = 2 和 (p.seeker_action 不为空) 或 (p.seeker_action 为空并且 p.employer_action = 'like')\nand j.deleted_at 是 null 有 action = 雇主喜欢)

我在 github 讨论上发布了这个并找到了解决方法,但我想知道是否有更好的解决方案。 Github laravel having issue discussion

【问题讨论】:

  • 请发布错误
  • 嗨 Seva,我已经编辑了上面的问题,请检查。
  • 当您只想获取employer-liking 时,为什么要检测所有不同的操作?你不能用->where('seeker_action', null)->where('employer_action', 'like')吗?
  • @jonas 这样做是为了使用过滤器和其他不同的操作以及雇主喜欢来获得分页
  • 我不明白你的回复。是否要选择其他操作?您的查询检测到所有操作,然后丢弃除employer-liking 之外的所有操作。

标签: pagination eloquent laravel-5.6 having having-clause


【解决方案1】:

你必须使用conditional WHERE clauses:

$data = DB::table('jobs as j')
    ->select('j.*')
    ->join('profiles_jobs as p', 'p.job_id', '=', 'j.id')
    ->where('p.profile_id', '=', 2)
    ->whereRaw("(p.seeker_action is not null) or (p.seeker_action is null and p.employer_action = 'like') and j.deleted_at is null")
    ->when($action === 'employer-liking', function($query) {
        $query->where('seeker_action', 'like')
            ->where('employer_action', 'like');
    })
    ->when($action === 'match', function($query) {
        $query->whereNull('seeker_action')
            ->where('employer_action', 'like');
    })
    ->when($action === 'rejected', function($query) {
        $query->where('seeker_action', 'like')
            ->where('employer_action', 'delete');
    });

$data = $data->paginate(10);

您还应该将whereRaw() 替换为where() and orWhere()

【讨论】:

  • 您能否就答案提供反馈?
猜你喜欢
  • 2017-02-05
  • 1970-01-01
  • 2023-03-15
  • 2013-11-15
  • 1970-01-01
  • 2022-10-16
  • 2018-02-06
  • 1970-01-01
  • 2023-02-03
相关资源
最近更新 更多