Laravel 5.4将json保存到数据库 [英] Laravel 5.4 save json to database
问题描述
帮助我将json保存到数据库.表字段类型-文本. 我有带演员表的模型
help me with save json to db. Table field type - text. I have Model with cast array
class Salesteam extends Model
{
protected $casts = [
'team_members' => 'array'
];
}
我想获取像这样的json {"index":"userId"}并将其存储到db. 示例:
I want get json like this {"index":"userId"} and store it to db. Example:
{"1":"7","2":"14","3":"25","4":"11"}
我在数据库中有Salesteam Model和'team_members'列,以保存所有用户ID属于该团队. 我的代码按ID查找组,获取所有"team_members"属性,然后向该组添加新用户.添加新的用户ID时,我想将所有用户存储为json格式并以递增索引存储.
I have Salesteam Model and 'team_members' column in db to saving all user id's belong to this team. My code find team by id, get all 'team_members' attribute and add new user to this team. I want store all users in json format and incrementing index when add new user id.
Salesteam属性:
Salesteam attributes:
"id" => 20
"salesteam" => "Admin"
"team_leader" => 0
"invoice_target" => 884.0
"invoice_forecast" => 235.0
"team_members" => "[1,66,71]"
"leads" => 0
"quotations" => 0
"opportunities" => 0
"notes" => ""
"user_id" => 1
"created_at" => "2017-09-22 09:13:33"
"updated_at" => "2017-09-22 13:10:25"
"deleted_at" => null
将新用户添加到团队的代码:
Code to add new user to team:
$salesTeam = $this->model->find($salesTeamId);
$teamMembers = $salesTeam->team_members;
$teamMembers[] = $userId;
$salesTeam->team_members = $teamMembers;
$salesTeam->save();
但是它存储到数据库数组并且没有索引
But it stores to db array and without index
"team_members" => "[1,34,56]"
从Laravel文档中-数组& JSON Casting 数组将自动序列化回JSON以进行存储"
From Laravel documentation - Array & JSON Casting "array will automatically be serialized back into JSON for storage"
我错了吗?
推荐答案
制作这样的json字符串
To make a json string like this
{"1":"7","2":"14","3":"25","4":"11"}
在php
中,将元素推入数组时必须传递一个键.例如
In php
, you must pass a key, when you're pushing elements to array. e.g.
$teamMembers = [];
$teamMembers['1'] = 7;
$teamMembers['2'] = 14;
...
如果不将其设为associative array
,则php
在转换为json字符串时会将其视为json数组.
If you don't make it an associative array
, php
will consider it as json array when converting to json string..
提示:您只能传递一个按键,它也可以使用. 例如
Tip: You may pass only one key and it will work too. e.g.
$test = [1, 2, 3, 4, 5, 6];
$test['10'] = 56;
echo json_encode($test);
输出:
"{"0":1,"1":2,"2":3,"3":4,"4":5,"5":6,"10":56}"
这篇关于Laravel 5.4将json保存到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!