Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ms-access/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel 查询whereHas和关系列的和_Laravel_Eloquent_Query Builder - Fatal编程技术网

Laravel 查询whereHas和关系列的和

Laravel 查询whereHas和关系列的和,laravel,eloquent,query-builder,Laravel,Eloquent,Query Builder,我有一个查询,用于使用关系表中的值之和添加自定义“余额”列 User::withCount(['transactions as balance' => function($query) { $query->select(\DB::raw('sum(credit_movement)')); }]); 这对于返回“balance”列非常有效 现在,我想过滤关于“余额”列的用户 ->where('balance'),终于让它工作了: User::whereHas('trans

我有一个查询,用于使用关系表中的值之和添加自定义“余额”列

User::withCount(['transactions as balance' => function($query) {
     $query->select(\DB::raw('sum(credit_movement)'));
}]);
这对于返回“balance”列非常有效


现在,我想过滤关于“余额”列的用户


->where('balance'),终于让它工作了:

User::whereHas('transactions', function($q) {
   $q->select(\DB::raw('SUM(credit_movement) as balance'))
       ->havingRaw('balance < 0');
   });
});
User::whereHas('transactions',函数($q){
$q->select(\DB::raw('SUM(贷方移动)作为余额'))
->哈文格罗(‘余额<0’);
});
});

尝试
balance\u count
而不是
balance
withCount
统计从选择返回的模型。它没有分组方式,因此您不能使用
having
。您可以尝试执行whereHas
,并在函数中执行groupBy/having。虽然没有尝试过,但不确定它是否能工作。我尝试过使用
whereHas()
进行操作,但无法使用sum编写where查询<代码>->where('sum(credit_movement)',
->whereRaw('sum(credit_movement)@dqureshiumar)返回
一般错误:1111无效使用组函数
User::withCount(['transactions as balance' => function($query) {
     $query->select(\DB::raw('sum(credit_movement)'));
}])
->having('balance', '<', 0); // won't work

// also:
->havingRaw('balance < 0'); // won't work
User::withCount(['transactions as balance' => function($query) {
     $query->select(\DB::raw('sum(credit_movement)'));
}])
   ->whereHas('transactions', function($q) {
      $q->whereRaw('sum(credit_movement), < ?', 0);
   });
User::whereHas('transactions', function($q) {
   $q->select(\DB::raw('SUM(credit_movement) as balance'))
       ->havingRaw('balance < 0');
   });
});