我有以下Laravel集合:
$sum = $payments->where('status', 'Executed')->pluck('request_text')
request_text
是一个内部具有amount
属性的JSON字段。有没有一种方法,我可以将所有金额相加而不用遍历json_decode
和foreach
?也许某些方法等效于pluck
,但用于从JSON提取?
答案 0 :(得分:0)
您可以使用type casting和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'];
}
}