【问题标题】:Access Index of Pivot Table in LaravelLaravel中数据透视表的访问索引
【发布时间】:2020-01-18 03:51:19
【问题描述】:

有没有办法可以访问如下所示的数据透视表???

array:18 [
  "id" => 4
  "user_id" => 5
  "price" => 8659
  "created_at" => "2020-01-17 14:08:06"
  "updated_at" => "2020-01-17 14:08:06"
  "pivot" => array:5 [
    "purchase_id" => 6
    "product_id" => 4
    "quantity" => "13"
    "unit_price" => "3212"
    "discount" => "11.00"
  ]
]

我想更新Pivot 表,我尝试了如下方法

       foreach($request->products as $product) {
            $purchase->products()->updateExistingPivot($product['id'], [
                'unit_price' => $product['unit_price'],
                'quantity' => $product['quantity'],
                'discount' => $product['discount'],
            ]);

            // dd($product);
        }

但出现错误message: "Undefined index: unit_price"

任何帮助,在此先感谢...

【问题讨论】:

  • 你试过这个 $product['pivot']['unit_price] 了吗?
  • @Qonvex620 还没有,我先试试吧..
  • @Qonvex620 就是这样,兄弟,您的解决方案完美运行..
  • 如果不是,那么你也可以像这样访问它 $product['pivot']->unit_price,这取决于你的数据透视是什么类型的数组或对象。
  • 谢谢,很高兴为您提供帮助。

标签: laravel eloquent many-to-many


【解决方案1】:

您的$product 中似乎没有unit_price 密钥,

尝试通过$product['pivot']调用它

$purchase->products()->updateExistingPivot($product['id'], [
                'unit_price' => $product['pivot']['unit_price'],
                'quantity' => $product['pivot']['quantity'],
                'discount' => $product['pivot']['discount'],
            ]);

【讨论】:

  • 我还是一样的issue
  • @z3r0 你的unit_price 似乎没有unit_price
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-10
  • 2016-11-14
相关资源
最近更新 更多