如何在 Laravel 中更新深层 json 数据

我需要更新 json 列中的数据。


代码

public function update(Request $request)

{

    $product = Product::findOrFail($request->input('productId'));

    $stock = $product->qty;

    $qty = $request->input('quantity');

    $userId = auth('api')->user()->id;

    

    if (!empty($qty)) {

        if ($qty < $stock) {


            $item = CartStorage::findOrFail($request->input('id'));

            $item->update([

                // I need this to happen

                // cart_data->quantity= $qty;

            ]);

            return response()->json([

                'data' => $item,

                'success' => 'Updated'

            ]);


        } else {

            return response()->json([

                'success' => 'Your quantity request is larger than our stock.'

            ]);

        }

    } else{ // 1. if nothing is given

        return response()->json([

            'success' => 'You need to input new quantity.'

        ]);

    }

}

我已在控制器中准备好所有数据,并且数据没有问题,我所需要做的就是更新本部分中提到的 json 数据:


$item = CartStorage::findOrFail($request->input('id'));

$item->update([

  // I need this to happen

  // cart_data->quantity= $qty;

]);

数据库截图

http://img4.mukewang.com/64b277020001f49d06500074.jpg

数据库数据cart_data列


"{

    \"name\":\"Option Product\",

    \"productId\":21,

    \"price\":\"370000\",

    \"quantity\":2,           ------> trying to update this value

    \"attributes\":{

        \"attr\":{

            \"name\":\"weight\",

            \"value\":\"2\"

        }

    },

    \"conditions\":[

        {

            \"name\":\"Colors\",

            \"value\":0

        }

    ]

}"

任何想法?


手掌心
浏览 124回答 2
2回答

德玛西亚99

如果您出于某种原因需要拉取 CartStorage 模型并用它执行其他操作,您可以像这样更新 cart_data:$item = CartStorage::findOrFail($request->input('id'));// Do whatever else you need$cartData = $item->cart_data;$cartData['quantity'] = 4;$item->update([&nbsp; &nbsp; 'cart_data' => $cartData]);

慕莱坞森

您可以直接在查询生成器中更新 JSON ,而无需先检索它,如下所示:// Assuming pk on cart_storages is idDB::table('cart_storages')   ->where('id', $request->input('id'))   ->update([       'cart_data->quantity' => $qty,   ]);重要的是要声明文档声明“MySQL 5.7+ 和 PostgreSQL 9.5+ 支持此操作”
打开App,查看更多内容
随时随地看视频慕课网APP