首页 > 解决方案 > 迁移 - 如何为 json 设置默认值?(MySQL)

问题描述

我有一个问题,我需要为我的设置 json 列设置一些值。

假设我的用户迁移文件中有这个:

$table->json('settings');

我的目标是将这些值设置为默认值:

'settings' => json_encode([
    'mail' => [
        'hasNewsletter' => false
    ],
    'time' => [
        'timezone' => ''
    ]
])

你会怎么做?

created我的第一种方法是在创建用户之后在我的 UserObserver 中设置值。

这会产生问题,即我的 UserFactory 无法正常工作。因为创建了一个用户,但设置值再次被用户观察者覆盖......

标签: laravel

解决方案


以下解决方案适用于 Eloquent 模型。

对于默认 JSON 数据,您可以在模型中执行类似的操作

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
   
protected $attributes = [
        'settings' => '{
            "mail": {
            "hasNewsletter" : false
            },
            "time": {
            "timezone" : ""
            }
        }'
    ];
}

{"mail": {"hasNewsletter" : false},"time": {"timezone" :""}如果您的输入为空,则默认值将在您的数据库中。但是,数据库中的现有值将保持不变,如果需要,必须手动更改。

如果你想保留现有的 DB 值null(和/或 null 时),但想通过 Eloquent 获取上述默认 json,你可以在模型中添加以下方法:

    protected function castAttribute($key, $value)
    {
        if ($this->getCastType($key) == 'array' && is_null($value)) {
            return '{
                    "mail":{
                        "hasNewsletter":false
                            },
                    "time":{
                         "timezone":""
                           }
                     }';
        }
        return parent::castAttribute($key, $value);
    }

注意:上面的 castAttribute 方法将为模型的所有 null json 列返回相同的 json/data。最好在这里设置空数组。

在 Laravel 5.8 中测试。参考:https ://laravel.com/docs/eloquent#default-attribute-values


推荐阅读