通读 JSON 字段并在没有 foreach 的情况下求和

Read through JSON field and sum without foreach

我有以下 Laravel collection:

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

request_text 是一个 JSON 字段,里面有一个 amount 属性。有没有一种方法可以在不循环使用 json_decodeforeach 的情况下对所有金额求和?也许某些方法等同于 pluck 但用于从 JSON?

中提取

您可能会使用 type casting and sum 方法获得结果:

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'];
    }
}