【问题标题】:How to get the sum of multiplied array keys from an array如何从数组中获取相乘的数组键的总和
【发布时间】: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


    【解决方案1】:

    这个 $this->orders()返回有很多关系数据。要从关系数据中获取项目集合,您应该使用get()。更新Cargo modal 中的代码。

        public function getProductMarginAttribute() {
            $orders = $this->orders()->get();
            $total = 0;
    
            foreach ($orders as $order) {
                $total += $order['qty'] * $order['price'];
            }
    
            return $total;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-06
      • 2022-01-02
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多