【发布时间】:2019-08-09 02:05:17
【问题描述】:
我有一个带有一些 json 列的模型。在我的播种机中,我得到了这样的东西:
/* dd($object)
{
'string_field1': "áéíóúÁÉÍÓÚñÑ",
'string_field2': "123",
'string_field3': "Normal string",
}
*/
MyModel::create([
'json_column1' => ["{$object->string_attribute1} - {$object->string_attribute2}"],
'json_column2' => [$object->string_attribute3],
]);
我的模型在它的 casts 数组中有 json 列
# MyModel.php
protected $casts = [
'json_column1' => 'array',
'json_column2' => 'array'
];
当我查看插入数据库 (PostgreSQL) 中的记录时,我发现了两个问题。
- 它们的值看起来像数组
- 所有 unicode 字符都被转义
基本上,它在后台使用 json_encode() 函数,没有任何选项,我想默认传递一些选项(JSON_FORCE_OBJECT 和 JSON_UNESCAPED_UNICODE),而不必每次都显式编写。
TL;DR
// this
MyModel::create([
'json_column1' => ["{$object->string_attribute1} - {$object->string_attribute2}"],
'json_column2' => [$object->string_attribute3],
]);
// automagically converts to this
MyModel::create([
'json_column1' => json_encode(["{$object->string_attribute1} - {$object->string_attribute2}"]),
'json_column2' => json_encode([$object->string_attribute3]),
]);
// but I want it to convert to this
MyModel::create([
'json_column1' => json_encode(["{$object->string_attribute1} - {$object->string_attribute2}"], JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE),
'json_column2' => json_encode([$object->string_attribute3], JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE),
]);
【问题讨论】:
-
尝试转换为受保护的对象 $casts = [ 'json_column1' => 'object', 'json_column2' => 'object' ];
-
完全没有变化。
-
github.com/laravel/framework/blob/5.8/src/Illuminate/Database/… 显示了转换类型会发生什么。看来我得手动放了。
标签: php json laravel serialization eloquent