【问题标题】:how to calculate the total of an order by multiplying the item price with it's quantity using laravel api?如何通过使用laravel api将商品价格乘以数量来计算订单总额?
【发布时间】:2020-01-06 05:50:08
【问题描述】:

我正在使用 post man(作为测试)发送一个 post 请求,其中包含以下 json 格式:

{

    "place_id": 2,

    "items": [
        {
            "id": 9,
            "quantity": 5
        },
        {
            "id": 8,
            "quantity": 3
        },
           {
            "id": 5,
            "quantity": 2
        }
    ]

}

现在,在客户确认他的订单之前,我需要做一些计算。每件商品都有自己的价格,我想计算每件商品的总价(价格 * 数量),但我对如何计算有点困惑。

这是我的代码(尝试)。它给了我价格的总和但不知道如何计算每件商品的(价格 * 数量):

     $items = $request->input('items',[]);

       $item_array = [];

        foreach ($items as $key=>$item)
        {
            $item_array[$key] = $item['id'];
        }

        $itemsPriceTotal = Item::whereIN('id',$item_array)->sum('price');
        $itemsPriceTotal =(int)($itemsPriceTotal);

【问题讨论】:

标签: php laravel eloquent


【解决方案1】:
$reqItems = $request->input('items');

// associative array of item ids and their respective quantities
$itemIdsQtys = [];

foreach($reqItems as $reqItem) {
  $itemIdsQtys[$reqItem['id']] = $reqItem['quantity'];
}

// get array of item ids and fetch their respective models
$ids = array_keys($itemIdsQtys);
$itemModels = Item::find($ids);

// calculate total
$priceTotal = 0;
foreach($itemModels as $model) {
  $subtotal = $model->price * $itemIdsQtys[$model->id];
  $priceTotal += $subtotal;
}

return $priceTotal;

【讨论】:

    【解决方案2】:

    我会利用模型修改器。

    见https://laravel.com/docs/5.8/eloquent-mutators:

    /**
     * Get the user's full name.
     *
     * @return string
     */
    public function getTotalCost()
    {
        // Example: $qty = SomeModel::Find()->where(['id' =. $this->id])->one()
    
        return $this->qty * $this->price;
    }
    
    

    然后使用$model->totalCost

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-26
      • 2021-01-07
      • 1970-01-01
      • 2021-04-17
      • 2018-08-05
      • 1970-01-01
      • 2020-05-17
      • 2020-03-18
      相关资源
      最近更新 更多