php Laravel:如何在数据库中存储 json 格式的数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37803214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel : How to store json format data in database?
提问by Hola
I want to store some json format data in database from a given array. But How i do store it using controller.
我想从给定的数组中将一些 json 格式的数据存储在数据库中。但是我如何使用控制器存储它。
Suppose I have json data like :
假设我有这样的 json 数据:
{"id":"bangladesh","divisions":[{"name":"Barisal"},{"name":"Chittagong"},{"name":"Dhaka"},{"name":"Khulna"},{"name":"Rajshahi"},{"name":"Rangpur"},{"name":"Sylhet"}]}
So far as I know in controller using json format is like this as I'm not fully aware of it.
据我所知,在控制器中使用 json 格式是这样的,因为我不完全了解它。
public function saveUser(Request $request)
{
$div=new Div();
$user->json = json_encode( array({"Date 1": {
{"id":"bangladesh","divisions":[{"name":"Barisal"},{"name":"Chittagong"},{"name":"Dhaka"},{"name":"Khulna"},{"name":"Rajshahi"},{"name":"Rangpur"},{"name":"Sylhet"}]}
$div->save();
return redirect('getList');
}
How do i save it in mySQL only the list of divisions in Division Model using Laravel Controller?
我如何使用 Laravel 控制器将其仅保存在分区模型中的分区列表中?
回答by delatbabel
You don't need to convert the array data to a JSON string yourself, use the Laravel $casts parameter on your model: https://laravel.com/docs/5.2/eloquent-mutators#attribute-casting
您不需要自己将数组数据转换为 JSON 字符串,在您的模型上使用 Laravel $casts 参数:https://laravel.com/docs/5.2/eloquent-mutators#attribute-casting
You should do something like this in your Div model:
你应该在你的 Div 模型中做这样的事情:
protected $casts = [
'divisions' => 'array',
];
回答by bbdangar
You can convert your Model to JSON format like
$model->toJson();
您可以将模型转换为 JSON 格式,例如
$model->toJson();
or
或者
if you have data in an array you can use json_encode(['id' => 1, 'name' => 'User 1']);
如果数组中有数据,则可以使用 json_encode(['id' => 1, 'name' => 'User 1']);
Laravel Schema does support JSON field types as well look https://laravel.com/docs/5.0/schema#adding-columns
Laravel Schema 确实支持 JSON 字段类型,也看看https://laravel.com/docs/5.0/schema#adding-columns
You can use text
field type as well to store JSON data.
您也可以使用text
字段类型来存储 JSON 数据。
回答by Jahirul Islam Mamun
Set your model
设置模型
protected $casts = [
'list' => 'array'
];
Here is the full code.
这是完整的代码。
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'primary_id',
'list'
];
protected $casts = [
'list' => 'array'
];
public function setMetaAttribute($value)
{
$list = [];
foreach ($value as $array_item) {
if (!is_null($array_item['key'])) {
$list[] = $array_item;
}
}
$this->attributes['list'] = json_encode($list);
}