如何使用UpdateExistingPivot通过ID更新Pivot表?

发布于 2025-02-09 02:43:02 字数 2597 浏览 4 评论 0原文

更新订单时,我想更新特定的Order_product行。

如果我有多个产品,这些产品具有相同的订单,但具有不同的颜色和数量。

order_product

IDOrder_idproduct_idcolorWentity
11 1 11 111 1
1 111 11

我要使用update> update exexistingPivot(),但它更新了像最后一个一样更新记录。

这就是我在更新顺序时发送的身体的样子:

{
"products": [
    {
        "id": 1,
        "color": "red",
        "quantity": 1
    },
    {
        "id": 1,
        "color": "blue",
        "quantity": 3
    },
    {
        "id": 2,
        "color": "black",
        "quantity": 5
    }
]}

这就是我希望看到

ID订单product_idproduct_id颜色数量
1 1111 21
11 11蓝色3
312黑色5

,获得此

IDorder_idproduct_id product_idcolor
11 11蓝色3
211蓝色3
312黑色5

ordersController


    public function update(AdminUpdateOrderRequest $request, $id)
    {
        $orderValidated = $request->validated();

        $order = Order::findOrFail($id);
        
        $order->update($orderValidated);

        foreach ($orderValidated['products'] as $product) {
            $order->products()->updateExistingPivot(
                $product['id'], [
                    'color' => $product['color'],
                    'quantity' => $product['quantity'],
                ]
            );
        }
        return OrderResource::make($order)->additional([
            'success' => true,
        ]);
    }

OrderModel

public function products()
    {
        return $this->belongsToMany(Product::class)->withPivot(['color', 'quantity', 'id'])->withTimestamps();
    }

I want to update specific order_product rows when update an order.

In case I have multiple products that have the same id at the same order but with different colors and quantities.

order_product table

idorder_idproduct_idcolorquantity
111red2
211blue1

I'm trying to use updateExistingPivot() but it updates the records like just the last one.

This is how the body I sent when updating order look like:

{
"products": [
    {
        "id": 1,
        "color": "red",
        "quantity": 1
    },
    {
        "id": 1,
        "color": "blue",
        "quantity": 3
    },
    {
        "id": 2,
        "color": "black",
        "quantity": 5
    }
]}

That's what I expected to see

idorder_idproduct_idcolorquantity
111red1
211blue3
312black5

Instead, got this

idorder_idproduct_idcolorquantity
111blue3
211blue3
312black5

OrdersController


    public function update(AdminUpdateOrderRequest $request, $id)
    {
        $orderValidated = $request->validated();

        $order = Order::findOrFail($id);
        
        $order->update($orderValidated);

        foreach ($orderValidated['products'] as $product) {
            $order->products()->updateExistingPivot(
                $product['id'], [
                    'color' => $product['color'],
                    'quantity' => $product['quantity'],
                ]
            );
        }
        return OrderResource::make($order)->additional([
            'success' => true,
        ]);
    }

OrderModel

public function products()
    {
        return $this->belongsToMany(Product::class)->withPivot(['color', 'quantity', 'id'])->withTimestamps();
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

子栖 2025-02-16 02:43:02
  1. 用于Manuttomany关系的枢轴表必须始终在两个模型ID上定义一个唯一的组合索引。
    例如,让我们看一下Laravel的扩展生成器如何定义用户和角色之间的枢轴表:

      schema :: create('cool_user',function(blueprint $ table){
                 $ table-> unsignedBiginteger('requ_id') - > index();
                 $ table-> forex('cool_id') - > references('id') - > on('requ') - > ondelete('cascade');
                 $ table-> unsignedBiginteger('user_id') - > index();
                 $ table-> forex('user_id') - > coreences('id') - > on('用户') - > ondelete('cascade');
                 $ table-> primary(['requ_id','user_id']);
     });
     

请参阅主要定义?这样,它可以确保“ cool_id”和“ user_id”之间的任何组合都是唯一的。

  1. 在那个示例(用户,角色)中,如果我们在枢轴表中有一些额外的colums,我们可以使用updateExistingPivot()两种方式:

      $ user-> roles() - > updateExistingPivot($ cole-> id,[cols => values]);
     $ coole-> useres() - > updateExistingPivot($ user-> id,[cols => values]);
     
  1. A pivot table for a manyToMany relationship must always define a unique combined index on both models ids.
    Let's look for example at how Laravel's extended generator defines a pivot table between User and Role:

         Schema::create('role_user', function (Blueprint $table) {
                 $table->unsignedBigInteger('role_id')->index();
                 $table->foreign('role_id')->references('id')->on('role')->onDelete('cascade');
                 $table->unsignedBigInteger('user_id')->index();
                 $table->foreign('user_id')->references('id')->on('user')->onDelete('cascade');
                 $table->primary(['role_id', 'user_id']);
     });
    

See the primary definition ? That way it ensures that any combination between 'role_id' and 'user_id' is unique.

  1. in that example (User, Role) and if we supposedly had some extra colums in our pivot table, we could use updateExistingPivot() either ways:

     $user->roles()->updateExistingPivot($role->id, [cols => values]);
     $role->users()->updateExistingPivot($user->id, [cols => values]);
    
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文