Laravel 5.4将json保存到数据库

时间:2017-09-22 12:31:50

标签: php json laravel

帮助我将json保存到db。表字段类型 - 文本。 我有带有投射数组的模型

class Salesteam extends Model 
{
    protected $casts = [        
        'team_members' => 'array'
    ];
}

我想让json像这样{" index":" userId"}并将其存储到db。 例如:

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

我有Salesteam模特和' team_members' db中的列,用于保存属于该团队的所有用户ID。 我的代码通过ID查找团队,获取所有' team_members'属性并向该团队添加新用户。我希望以json格式存储所有用户,并在添加新用户ID时递增索引。

Salesteam属性:

"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

将新用户添加到团队的代码:

$salesTeam = $this->model->find($salesTeamId);
$teamMembers = $salesTeam->team_members;
$teamMembers[] = $userId;
$salesTeam->team_members = $teamMembers;
$salesTeam->save();

但是它存储到db数组而没有索引

"team_members" => "[1,34,56]"

从Laravel文档 - Array & JSON Casting"数组将自动序列化为JSON以进行存储"

我哪里错了?

4 个答案:

答案 0 :(得分:1)

制作像这样的json字符串

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

php中,当您将元素推送到数组时,必须传递一个键。 e.g。

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

如果您没有将其设为associative arrayphp会在转换为json字符串时将其视为json数组。

提示:您可以只传递一个密钥,它也会起作用。 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}"

PHP-Reference

答案 1 :(得分:0)

如果你得到"[1,34,56]",只需执行json_decode($team_members)

你会得到这个:

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

答案 2 :(得分:0)

简单解决方案

$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

答案 3 :(得分:0)

只需使用

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

那应该是全部。