为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
手掌心 2023-07-15 18:37:23
我需要更新 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;]);数据库截图数据库数据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        }    ]}"任何想法?
查看完整描述

2 回答

?
德玛西亚99

TA贡献1770条经验 获得超3个赞

如果您出于某种原因需要拉取 CartStorage 模型并用它执行其他操作,您可以像这样更新 cart_data:


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


// Do whatever else you need


$cartData = $item->cart_data;

$cartData['quantity'] = 4;


$item->update([

    'cart_data' => $cartData

]);


查看完整回答
反对 回复 2023-07-15
?
慕莱坞森

TA贡献1810条经验 获得超4个赞

您可以直接在查询生成器中更新 JSON ,而无需先检索它,如下所示:

// Assuming pk on cart_storages is id

DB::table('cart_storages')

   ->where('id', $request->input('id'))

   ->update([

       'cart_data->quantity' => $qty,

   ]);

重要的是要声明文档声明“MySQL 5.7+ 和 PostgreSQL 9.5+ 支持此操作”


查看完整回答
反对 回复 2023-07-15
  • 2 回答
  • 0 关注
  • 120 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信