用 whereHas 和关系列的总和查询
Query with whereHas and sum of relationship column
我有一个查询,要使用关系 table 中的值总和来添加自定义“余额”列。
User::withCount(['transactions as balance' => function($query) {
$query->select(\DB::raw('sum(credit_movement)'));
}]);
这对 returning “余额”栏很有效。
现在,我想过滤有关“余额”列的用户。
->where('balance', '<', 0);
如果我将它链接到查询,它将不起作用,因为“余额”列不存在。
User::withCount(['transactions as balance' => function($query) {
$query->select(\DB::raw('sum(credit_movement)'));
}])
->where('balance', '<', 0);
我试过使用
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
但是 none 这些作品。
Unknown column 'balance' in 'having clause'
我希望查询 return 仅余额小于 0 的用户。(我想在查询生成器中实现它,而不是在集合中 ->filter()
。
更新:
我尝试使用 whereHas()
但无法正确编写
User::withCount(['transactions as balance' => function($query) {
$query->select(\DB::raw('sum(credit_movement)'));
}])
->whereHas('transactions', function($q) {
$q->whereRaw('sum(credit_movement), < ?', 0);
});
Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' < ?)
终于成功了:
User::whereHas('transactions', function($q) {
$q->select(\DB::raw('SUM(credit_movement) as balance'))
->havingRaw('balance < 0');
});
});
我有一个查询,要使用关系 table 中的值总和来添加自定义“余额”列。
User::withCount(['transactions as balance' => function($query) {
$query->select(\DB::raw('sum(credit_movement)'));
}]);
这对 returning “余额”栏很有效。
现在,我想过滤有关“余额”列的用户。
->where('balance', '<', 0);
如果我将它链接到查询,它将不起作用,因为“余额”列不存在。
User::withCount(['transactions as balance' => function($query) {
$query->select(\DB::raw('sum(credit_movement)'));
}])
->where('balance', '<', 0);
我试过使用
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
但是 none 这些作品。
Unknown column 'balance' in 'having clause'
我希望查询 return 仅余额小于 0 的用户。(我想在查询生成器中实现它,而不是在集合中 ->filter()
。
更新:
我尝试使用 whereHas()
但无法正确编写
User::withCount(['transactions as balance' => function($query) {
$query->select(\DB::raw('sum(credit_movement)'));
}])
->whereHas('transactions', function($q) {
$q->whereRaw('sum(credit_movement), < ?', 0);
});
Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' < ?)
终于成功了:
User::whereHas('transactions', function($q) {
$q->select(\DB::raw('SUM(credit_movement) as balance'))
->havingRaw('balance < 0');
});
});