Laravel:更新嵌套的json对象 [英] Laravel: Update a nested json object
问题描述
我在数据库中有一列用于保存用户设置.数据结构如下所示:
I have a column in my db for saving a users' settings. This is what the data structure looks like:
{"email":{"subscriptions":"{\"Foo\":true,\"Bar\":false}"}}
我正在使用Vue切换按钮来更改每个属性的状态(是/否).一切似乎都正常,但是当我保存时,我要清除结构并保存更新的值,如下所示:
I am using a vue toggle to change the status of each property (true/false). Everything seems to be working, however when I save, I am wiping out the structure and saving the updated values like this:
{\"Foo\":true,\"Bar\":false}"}
php
$user = auth()->user();
$array = json_decode($user->preferences['email']['subscriptions'], true);
dd($array);
以上让我:
array:2 [
"Foo" => true
"Bar" => false
]
到目前为止一切都很好...
So far so good...
$preferences = array_merge($array, $request->all());
dd($preferences);
得到我:
array:2 [
"Foo" => true
"Bar" => true
]
好极了-这些值现在可以提取从axios请求传入的值.接下来更新用户数据:
Great - the values are now picking up the values passed in from the axios request. Next up; update the user's data:
$user->update(compact('preferences'));
现在我的数据如下:
{"Foo":true,"Bar":true}
这些值不再嵌套;我已经消灭了 email
和 subscriptions
.
The values are no-longer nested; I've wiped out email
and subscriptions
.
我已经尝试过了:
$user->update([$user->preferences['email']['subscriptions'] => json_encode($preferences)]);
但是它似乎没有保存数据.如何使用 $ preferences
变量更新数据-并保持数据正确嵌套?
But it doesn't seem to save the data. How can I use the $preferences
variable to update the data - and keep the data nested correctly?
推荐答案
您可以使用所需的结果json具有的结构创建一个数组.因此,对于此json:
You can create an array with the structure you want the resulting json to have. So, for this json:
{
"email":{
"subscriptions":{
"Foo":true,
"Bar":false
}
}
}
您可以创建一个像这样的数组:
you can create an array like this:
[
'email' => [
'subscriptions' => [
'Foo' => true,
'Bar' => false
]
]
]
然后,对整个结构进行编码:
an then, encode the entire structure:
json_encode([
'email' => [
'subscriptions' => [
'Foo' => true,
'Bar' => false
]
]
]);
因此,在您的代码中,因为您已经在$ preferences变量中有了嵌套数组,所以我认为这应该起作用:
So, in your code, as you already have the nested array in the $preferences variable, I think this should work:
$json_preferences = json_encode([
'email' => [
'subscriptions' => $preferences
]
]);
然后,您可以更新用户的首选项"属性(例如):
Then you can update the user 'preferences' attribute (just for example):
User::where('id', auth()->user()->id)->update(['preferences' => $json_preferences]);
或
$user = auth()->user();
$user->preferences = $json_preferences;
$user->save();
这篇关于Laravel:更新嵌套的json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!