【问题标题】:How to do this in laravel, Subquery where count如何在 laravel 中执行此操作,子查询 where count
【发布时间】:2017-09-27 14:09:48
【问题描述】:

我正在尝试在 Laravel 中实现此查询

"SELECT * FROM jobs 
WHERE status = 1 AND 
taskerCount = (SELECT count(*) FROM jobRequests WHERE status = 1 AND job_id = 
jobs.id)"

这是我尝试过的;

Auth::user()->jobs
        ->where('status', 1)
        ->where('taskerCount', function ($q) {
            $q->where('status', 1)
              ->where('job_id', $q->id)->count();
        });

但我得到了错误:

Closure 类的对象无法转换为 int。

【问题讨论】:

  • 你不能使用 ->count 构建器,你只能在语句执行后使用它。您需要使用原始 sql 来选择它作为构建器返回的内容。
  • 即使我将其更改为 $q->select(DB::raw('count(*)')) ->where('status', 1) ->where('job_id' , $q->id);我仍然得到同样的错误。而且我不确定 $q->id 返回什么。
  • 查看我的答案以获取我过去使用过的示例

标签: php mysql laravel orm eloquent


【解决方案1】:

使用原始表达式代替 -count()。

你可以查看这个documentation here

来自 laravel 的原始查询示例:

$users = DB::table('users')
                 ->select(DB::raw('count(*) as user_count, status'))
                 ->where('status', '<>', 1)
                 ->groupBy('status')
                 ->get();

确保将计数定义为名称。

【讨论】:

    猜你喜欢
    • 2013-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-30
    • 1970-01-01
    相关资源
    最近更新 更多