【发布时间】:2021-10-27 22:45:18
【问题描述】:
一个cargo 有很多orders。一个order 有一个quantity 和一个price。对于cargo 中的每个order,我想将quantity * price 的总和作为单个值返回。
cargo 集合返回数据为:
{
"data": {
"cargo_id": 4,
"name": "Cargo Name",
"qty": "366200.00",
"cost": 140,
"product_id": 1,
"product": {
"id": 1,
"name": "Sample Product"
},
"orders": [
{
"id": 1,
"cargo_id": 4,
"qty": 14200,
"price": "500"
},
{
"id": 4,
"cargo_id": 4,
"qty": 12000,
"price": "500"
},
{
"id": 6,
"cargo_id": 4,
"qty": 5600,
"price": "500"
}
],
"comments": "sample",
}
}
我尝试在 Cargo 类中使用 Eloquent 访问器:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Cargo extends Model
{
protected $guarded = [];
protected $appends = [
'product_margin'
];
public function orders() {
return $this->hasMany(Order::class);
}
public function getProductMarginAttribute() {
$orders = $this->orders();
$total = 0;
foreach ($orders as $order) {
$total += $order['qty'] * $order['price'];
}
return $total;
}
}
但是product_margin 返回0。我怎样才能让它工作?
【问题讨论】:
标签: php arrays laravel eloquent