根据模型方法结果归还收益

时间:2018-12-15 17:06:35

标签: laravel eloquent

我有一个具有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);的事情吗?

1 个答案:

答案 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();