我有一个具有Credits关系的用户模型。
public function credits()
{
return $this->hasMany('App\Credit');
}
我想返回所有他们的贷方余额大于0的用户。现在,我有两种方法:一个用于检索用户积累的总积分,另一种用于检索用户已花费的积分。
public function creditsIncome()
{
return $this->credits->where('type', 0)->sum('amount');
}
public function creditsExpense()
{
return $this->credits->where('type', 1)->sum('amount');
}
要获得余额,我有第三种方法:
public function creditsBalance()
{
return $this->creditsIncome() - $this->creditsExpense();
}
有什么办法做类似User::where('creditsBalance', '>', 0);
的事情吗?
答案 0 :(得分:1)
您可以使用修改后的withCount()
:
User::withCount([
'credits as income' => function($query) {
$query->select(DB::raw('sum(amount)'))->where('type', 0);
},
'credits as expense' => function($query) {
$query->select(DB::raw('sum(amount)'))->where('type', 1);
}
])->having(DB::raw('income - expense'), '>', 0)->get();