【问题标题】:Is there a way to customize JSON serialization when inserting/updating a model in Laravel?在 Laravel 中插入/更新模型时,有没有办法自定义 JSON 序列化?
【发布时间】: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_OBJECTJSON_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),
]);

【问题讨论】:

标签: php json laravel serialization eloquent


【解决方案1】:

在 Model 实例中转换属性实际上只是实现 mutator 和 accessor 的一种简化方式。因此,您可以改为删除演员表并自己定义这些,授予您任何您想要的行为。

https://laravel.com/docs/5.8/eloquent-mutators

MyModel.php

class MyModel extends Model
{
    ...

    // fires when storing a value
    public function setJsonColumn1Attribute($value)
    {
        $this->attributes['json_column1'] = json_encode([$value], JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE);
    }

    // fires when retrieving a value
    public function getJsonColumn1Attribute($value)
    {
        return json_decode($value);
    }
}

控制器

MyModel::create([
   'json_column1' => "{$object->string_attribute1} - {$object->string_attribute2}",
]);

【讨论】:

    猜你喜欢
    • 2010-12-22
    • 2021-02-18
    • 1970-01-01
    • 2014-06-27
    • 2019-08-17
    • 1970-01-01
    • 2016-11-09
    • 2020-01-12
    • 1970-01-01
    相关资源
    最近更新 更多