John Davidson

php - How to get the sum of multiplied array keys from an array

0 comments
Message:


A cargo has many orders. An order has a quantity and a price. For every order in a cargo, I want to return the sum of quantity * price as a single value.


A cargo collection returns data as:


{
"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",
}
}

I have tried using an Eloquent Accessor in the Cargo class as:


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

But product_margin returns 0. How can I get this working?



My Answer:
You are close, but there is a small mistake in your code. Instead of calling the `orders()` method, you should call the `orders` property directly to access the orders related to the cargo. Here is the corrected code:

php
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;
}
}


By making this change, the `getProductMarginAttribute` accessor should now correctly calculate the sum of quantity * price for all orders related to the cargo.

Rate this post

5 of 5 based on 2783 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us