Laravel withCount()返回null

时间:2018-11-08 07:16:05

标签: php laravel

我需要计算多对多关系子查询的结果。

  val windowSpec = Window
    .orderBy(col("ts_begin").asc)
    .rowsBetween(Window.currentRow, nBuckets-1)

此代码无效。返回null。

但是,这很好,并且可以成功添加users_count列:

return $q->withCount(['users' => function($q) {
    $q->select("Users.Id as Id_user","Users.Name");
}])->get()

但是我需要进行select子查询以从关系中选择特定的列,因此我需要第一个变体开始工作。

非常感谢!

1 个答案:

答案 0 :(得分:0)

当您使用CountwithCount方法时,查询生成器会执行select count(id) as aggregate

如果在withCount的条件参数中,您覆盖select部分。坏了

return $q->withCount(['users' => function($q) {
    //here you are supposed to do condition, not a select
    $q->select("Users.Id as Id_user","Users.Name");
}])->get()

如果需要用户名和用户名,请使用with

return $q->withCount(['users'])
    ->with(['users' => function($q) {
        $q->select("Users.Id as Id_user","Users.Name");
    }])
    ->get()