亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 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 關注
  • 208 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號