【问题标题】:Insert price to the pivot table将价格插入数据透视表
【发布时间】:2021-11-15 03:17:12
【问题描述】:

我正在尝试使用数组将数据插入数据透视表 order_service 我遵循以下代码:https://blog.quickadminpanel.com/master-detail-form-in-laravel-jquery-create-order-with-products/

列的数量和服务插入正确,但价格没有,我不知道为什么?

order_service 表:

  Schema::create('order_service', function (Blueprint $table) {
            $table->foreignId('service_id');
            $table->foreignId('order_id');
            $table->float('price')->default(0);
            $table->integer('qty')->default(0);

            $table->primary(['service_id','order_id']);

订单控制器:

 $services = $request->input('services', []);
        $quantities = $request->input('qty', []);
        $price=$request->input('price', []);
        for ($service=0; $service < count($services); $service++) {
            if ($services[$service] != '') {
                $order->services()->attach($services[$service], ['qty' => $quantities[$service]], ['price' => $price[$service]]);

            }

使用 dd($request):

 "services" => array:2 [▼
        0 => "3"
        1 => "2"
      ]
      "qty" => array:2 [▼
        0 => "861"
        1 => "748"
      ]
      "price" => array:2 [▼
        0 => "20"
        1 => "40"

dd($price[$service])

"20"

数据库输出

| order_id |  service_id    |price | qty|
| -------- | -------------- |______|____|
| 2074     | 2              |0.00  |748 |
| 2074     | 3              |0.00  |861 |

有人可以帮忙吗?

【问题讨论】:

    标签: php sql arrays laravel


    【解决方案1】:

    在您的控制器中,您误用了attach() 方法:

    $order->services()->attach(
        $services[$service], 
        ['qty' => $quantities[$service]], 
        ['price' => $price[$service]]  // something wrong with your arrays here, it only needs one in the second argument
    );
    

    attach() 方法应该这样使用:

    $order->services()->attach(
        $services[$service], [
            'qty' => $quantities[$service], 
            'price' => $price[$service] 
        ]
    );
    

    第二个参数是一个包含所有附加枢轴值的数组。

    【讨论】:

      【解决方案2】:

      您好,通过在单个数组中附加值来尝试使用此代码

      $order->services()->attach($services[$service], ['qty' => $quantities[$service], 'price' => $price[$service]]);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-24
        • 1970-01-01
        • 1970-01-01
        • 2021-06-22
        • 1970-01-01
        • 1970-01-01
        • 2020-09-19
        • 2023-02-08
        相关资源
        最近更新 更多