通读JSON字段并求和而不用foreach

时间:2019-12-18 23:36:58

标签: laravel laravel-5 laravel-collection

我有以下Laravel集合:

$sum = $payments->where('status', 'Executed')->pluck('request_text')

request_text是一个内部具有amount属性的JSON字段。有没有一种方法,我可以将所有金额相加而不用遍历json_decodeforeach?也许某些方法等效于pluck,但用于从JSON提取?

1 个答案:

答案 0 :(得分:0)

您可以使用type castingsum方法获得结果:

class Payment extends Model
{
    protected $casts = [
        'request_text' => 'object',
    ];

    public function getAmountAttribute()
    {
        return $this->request_text->amount;
    }
}


// Both of these are gonna work.
$sum = Payment::whereStatus('Executed')->sum(function ($payment) {
    return $payment->request_text->amount;
});

$sum = Payment::whereStatus('Executed')->sum->amount;

您还可以将request_text强制转换为数组,以便可以以不同的方式访问数量。

class Payment extends Model
{
    protected $casts = [
        'request_text' => 'array',
    ];

    public function getAmountAttribute()
    {
        return $this->request_text['amount'];
    }
}