Php 在laravel中保存JSON字符串
我正在尝试将JSON字符串保存到数据库中 这是我得到的错误:Php 在laravel中保存JSON字符串,php,json,laravel,eloquent,laravel-5.1,Php,Json,Laravel,Eloquent,Laravel 5.1,我正在尝试将JSON字符串保存到数据库中 这是我得到的错误: exception 'ErrorException' with message 'preg_replace(): Parameter mismatch, pattern is a string while replacement is an array 这就是我的JSON的样子: "metadata": { "is_ivr": 0, "is_upgradable": 1, "is_sms": 0,
exception 'ErrorException' with message 'preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
这就是我的JSON的样子:
"metadata": {
"is_ivr": 0,
"is_upgradable": 1,
"is_sms": 0,
"is_design": 0,
"threshold_amount": 0,
"post_threshold": 0,
"pre_threshold": 0
}
我想将元数据的值保存为字符串
我试着这样做:
$data = $request->input('data');
$data['metadata'] = json_encode($data['metadata']);
dd($data)的结果代码>
使用内爆()
并用逗号分隔,或者如果您愿意,可以通过直接调用数组的索引$data['metadata'][index]
发生的情况是,您正在调用数组上的正则表达式而不是值。老实说,我不知道现在发生了什么,但打开您的模型(我不知道它的名称,因为您没有显示它),然后填充:
protected $casts = [
'metadata' => 'array',
];
假设你还没做
现在,当您将数据插入数据库时,不要使用任何json\u encode
,只需使用:
$data = $request->input('data');
没有:
$data['metadata'] = json_encode($data['metadata']);
使用casts
property Laravel将在插入数据库时自动将数组数据转换为json,并在从数据库获取数据时自动运行json\u decode
以获取数组。在将json保存到数据库之前,您需要序列化数据,例如:
$data = serialize( json_encode( $data['metadata'] ) );
// Insert $data into the DB
现在,如果您想在PHP中重用数据库中的数据,则需要运行相反的非序列化程序
$raw_data = // query to get the data from the DB
$data = unserialize( $raw_data );
这将允许您保存数据结构,如数组
生成值的可存储表示形式
你确定错误在这里吗?显示整个代码和dd($data)的结果代码>您是否使用雄辩?用于创建记录?你使用的是什么版本的Laravel?为什么编码而不是解码?@MarcinNabiałek我使用的是Laravel 5.1。是的,使用雄辩来创造记录。我已经添加了dd($data)的结果;我去办公室后会试试这个。
$raw_data = // query to get the data from the DB
$data = unserialize( $raw_data );