gpt4 book ai didi

laravel - 迁移 - 如何设置 json 的默认值? (MySQL)

转载 作者:行者123 更新时间:2023-12-04 12:44:16 26 4
gpt4 key购买 nike

我的问题是我需要为我的设置 json 列设置一些值。

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

$table->json('settings');

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

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

你会怎么做?

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

这会产生问题,即我的 UserFactory 无法正常工作。因为创建了 User 但设置值再次被 UserObserver 覆盖...

最佳答案

以下解决方案适用于 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":""}。但是,数据库中的现有值将保持不变,如果需要,必须手动更改。

如果你想保留现有的数据库值 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 方法将为模型的所有空 json 列返回相同的 json/data。这里最好设置空数组。

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

关于laravel - 迁移 - 如何设置 json 的默认值? (MySQL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53489881/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com