【问题标题】:Foreach each product then get total price? [duplicate]Foreach 每个产品然后得到总价? [复制]
【发布时间】:2020-05-17 17:15:52
【问题描述】:

我有这两张桌子:

    Orders: 
    id - status -user_id - address_id 
    1     await    1          1 

    products:
    id -  name -   price  - quantity
    1     test1    100$       5 
    2     test2    50$        5 


    order_product:
    order_id - product_id - quantity
    1           1            2
    1           2            2

订单模型中的关系:

public function products()
{
    return $this->belongsToMany('App\Models\Product')->withPivot('quantity')->withTimestamps();
}

我需要这个:

foreach 每个产品,然后将每个产品的价格与order_product(quantity)?? 中的第三个表相乘

我的闭嘴:

 foreach ($order->products as $product) {

        $total_price = $product->pivot->quantity * $product->price;

  }

我需要在此之后将总价格与枢轴(数量)相乘?

【问题讨论】:

标签: php laravel


【解决方案1】:

订单和产品的关系是多对多的。

加入:

你可以使用左连接:

$product_query = Product::leftjoin('order_product', 'order_product.product_id', '=','product.id')
       ->select("product.*", DB::raw("SUM(product.price * order_product.quantity) AS total_price"));

所以你可以用total_price获得产品:

$product_query->find(1)->total_price;

访问者:

你可以使用访问器来获取属性,

在您的 Product 模型中,使用 withPivot 添加数据透视表的数据,并使用访问器:

    protected $appends = ["total_price"];

    public function orders()
    {
        return $this->belongsToMany(Order::class, 'order_product', 'product_id', 'order_id')
                   ->withPivot('quantity') // You need to add the pivot datas here.
                  ->withTimestamps();
    }

    // Add accessor here:
    public function getTotalPriceAttribute() {
        return $this->price * $this->orders->sum('pivot.quantity');
    }

所以你可以用total_price获得产品:

Product::first()->total_price;

【讨论】:

    【解决方案2】:

    试试这个,

    foreach ($order->products as $product) {
    
            $total_price += $product->pivot->quantity * $product->price;
    
      }
    

    只需加上 +=,这样乘法后它就会被加到总数中。

    【讨论】:

      【解决方案3】:

      试试这个

      在你的模型中

      public function orders()
      {
          return $this->belongsToMany(Order::class, 'order_product', 'product_id', 'order_id')
                     ->withPivot('quantity')
                     ->withTimestamps();
      } 
      

      改变

      $total_price = 0;
      
      foreach ($order->products as $product) {
      
              $total_price += $product->pivot->quantity * $product->price;
      
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-10
        • 2020-04-23
        • 2022-01-09
        • 2019-06-30
        • 1970-01-01
        相关资源
        最近更新 更多