我有3个字段“名称”,“电子邮件”和“ URL”。这3个字段被强制转换为数据库中1列中的json。
现在,如果仅填写URL,我只想在数据库中保存{url: "value"}
。如果您填写电子邮件和姓名,我只想在数据库中保存{name: "john", email: "john@gmail.com"}
。
这是我尝试执行的操作:
Text::make('To Name', 'toName')
->sortable()
->fillUsing(
function ($request, $model) {
return $request->toName;
}
),
Text::make('To Email', 'toEmail')
->sortable()
->fillUsing(
function ($request, $model) {
return $request->toEmail;
}
),
Text::make('To Url', 'toUrl')
->sortable()
->fillUsing(
function ($request, $model) {
return $request->toUrl;
}
),
但是我一直收到此错误:
一般错误:1364字段“至”没有默认值
我要返回错误的东西吗?
答案 0 :(得分:0)
检查此代码,使用Laravel mutator和fillUsing中的一些更改。注意toName,toEmail,toUrl是虚拟属性,而to_json包含模型中这些列的json值!
// database\migrations\2019_08_28_045853_create_infos_table.php
...
Schema::create('infos', function (Blueprint $table) {
$table->bigIncrements('id');
$table->timestamps();
$table->string('label',100);
$table->json('to_json');
});
// app\Nova\Info.php
...
public function fields(Request $request)
{
return [
ID::make()->sortable(),
Text::make('Label'),
Text::make('To Name', 'toName')
->sortable()
->fillUsing(
function ($request, $model) {
if(!empty($request->toName)){
if(!empty($model['to_json'])){
$json = json_decode($model['to_json'],true);
}else{
$json = [];
}
$json['name'] = $request->toName;
$model['to_json'] = json_encode($json);
}
}
),
Text::make('To Email', 'toEmail')
->sortable()
->fillUsing(
function ($request, $model) {
if(!empty($request->toEmail)){
if(!empty($model['to_json'])){
$json = json_decode($model['to_json'],true);
}else{
$json = [];
}
$json['email'] = $request->toEmail;
$model['to_json'] = json_encode($json);
}
}
),
Text::make('To Url', 'toUrl')
->sortable()
->fillUsing(
function ($request, $model) {
if(!empty($request->toUrl)){
if(!empty($model['to_json'])){
$json = json_decode($model['to_json'],true);
}else{
$json = [];
}
$json['url'] = $request->toUrl;
$model['to_json'] = json_encode($json);
}
}
),
];
}
// app\Info.php
...
class Info extends Model
{
public function gettoNameAttribute(){
if(empty($this->attributes['to_json'])){
return "";
}
$json = $this->attributes['to_json'];
$result = json_decode($json,true);
if(!empty($result['name'])){
return $result['name'];
}else{
return "";
}
}
public function gettoEmailAttribute(){
if(empty($this->attributes['to_json'])){
return "";
}
$json = $this->attributes['to_json'];
$result = json_decode($json,true);
if(!empty($result['email'])){
return $result['email'];
}else{
return "";
}
}
public function gettoUrlAttribute(){
if(empty($this->attributes['to_json'])){
return "";
}
$json = $this->attributes['to_json'];
$result = json_decode($json,true);
if(!empty($result['url'])){
return $result['url'];
}else{
return "";
}
}
}