laravel - 迁移 - 如何为 json 设置默认值?(MySQL)
问题描述
我有一个问题,我需要为我的设置 json 列设置一些值。
假设我的用户迁移文件中有这个:
$table->json('settings');
我的目标是将这些值设置为默认值:
'settings' => json_encode([
'mail' => [
'hasNewsletter' => false
],
'time' => [
'timezone' => ''
]
])
你会怎么做?
created
我的第一种方法是在创建用户之后在我的 UserObserver 中设置值。
这会产生问题,即我的 UserFactory 无法正常工作。因为创建了一个用户,但设置值再次被用户观察者覆盖......
解决方案
以下解决方案适用于 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
推荐阅读
- c - 通过删除子数组使数组左侧和右侧的总和相等
- laravel-5 - finally() 在另一个应用程序中无法在 Vuejs 中工作
- google-sheets - 基于具有匹配数字的两个单元格的 Google 表格条件格式
- angular - 如何禁止角度材料输入字段的错误输入
- if-statement - 这是关于 Else/If 函数的开始问题
- modelica - Modelica - 在模拟期间冻结特定时间值
- graph-theory - 需要哪些索引信息来快速检查有向无环图的节点是否在另一个节点之前、之后或平行?
- github - 为什么 apt-get 在 Ubuntu 18.04 版本上找不到 github-ee 包?
- ruby - 哈希中具有多个值的重复值的总和
- java - 是否可以在 close() 之后重新打开文件而不在同一个 java 程序中再次创建它?