基于模型方法结果的退货收集 [英] Return collection based on model method result

查看:73
本文介绍了基于模型方法结果的退货收集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有Credits关系的用户模型.

I have a User model with a Credits relation.

public function credits()
{
    return $this->hasMany('App\Credit');
}

我想返回其贷方余额大于0的所有用户.现在,我有两种方法:一个用于检索用户积累的总积分,另一种用于检索用户已花费的积分.

I'd like to return all users where their credit balance is greater than 0. Right now, I have two methods; one to retrieve the total credits the user has amassed and another to retrieve the credits the user has spent.

public function creditsIncome()
{
    return $this->credits->where('type', 0)->sum('amount');
}

public function creditsExpense()
{
    return $this->credits->where('type', 1)->sum('amount');
}

要获得余额,我有第三种方法:

To get the balance, I have a third method:

public function creditsBalance()
{
    return $this->creditsIncome() - $this->creditsExpense();
}

有什么办法做像User::where('creditsBalance', '>', 0);这样的事情吗?

Is there any way to do something like User::where('creditsBalance', '>', 0);?

推荐答案

您可以使用修改后的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();

这篇关于基于模型方法结果的退货收集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆