简体   繁体   中英

Laravel 5.4 save json to database

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'
    ];
}

I want get json like this {"index":"userId"} and store it to db. Example:

{"1":"7","2":"14","3":"25","4":"11"}

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 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]"

From Laravel documentation - Array & JSON Casting "array will automatically be serialized back into JSON for storage"

Where i'm wrong?

To make a json string like this

{"1":"7","2":"14","3":"25","4":"11"}

In php , you must pass a key, when you're pushing elements to array. eg

$teamMembers = [];
$teamMembers['1'] = 7;
$teamMembers['2'] = 14;
...

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. eg

$test = [1, 2, 3, 4, 5, 6];

$test['10'] = 56;

echo json_encode($test);

Output:

"{"0":1,"1":2,"2":3,"3":4,"4":5,"5":6,"10":56}"

PHP-Reference

Simply use

$teamMembers = json_encode($salesTeam->team_members);

That should do be all.

if you get this "[1,34,56]" just do json_decode($team_members)

and you will have this:

array:3 [▼
  0 => 1
  1 => 34
  2 => 56
]

Simple Solution

$books = App\Book::all();
$user->books = $books->toJson();
$user->save(); //example: userid -> 2

$user = App\User::find(2);
$userBooks = json_decode($user->books, true); // to generate object again

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM