我需要更新 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
]);

慕萊塢森
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+ 支持此操作”
- 2 回答
- 0 關注
- 208 瀏覽
添加回答
舉報
0/150
提交
取消