php - Laravel 8 firstOrCreate 不使用 $fillable
问题描述
我的控制器中有这段代码:
$createAccreditorAccount = User::firstOrCreate(
['name' => "Accreditor"],
['nonofficial_category_id' => 0],
['role' => "accreditor"],
['email' => "accreditor@cvsucarmona.com"],
['password' => Hash::make('accreditor_cvsucarmona')],
['email_verified_at' => now()]
);
我得到的错误是这样的:
SQLSTATE[HY000]: General error: 1364 Field 'role' doesn't have a default value (SQL: insert into `users` (`name`, `nonofficial_category_id`, `updated_at`, `created_at`) values (Accreditor, 0, 2021-05-19 11:36:35, 2021-05-19 11:36:35))
在错误显示中,它似乎是列role
,email
并password
没有填写我的记录。我很确定我已将这些列包含在我的$fillable
.
下面是我的User
模型:
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'role',
'subcategory',
'email',
'password',
'nonofficial_category_id',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function nonOfficialsCategories()
{
return $this->belongsTo(NonOfficialsCategories::class, 'nonofficial_category_id');
}
}
解决方案
您不需要在其自己的数组中指定每个字段值并将它们作为单独的参数提供,firstOrCreate()
只需要 2 个参数,第一个数组是要检查的唯一字段,第二个参数是要插入或更新的值数组。应该更像这样...
$createAccreditorAccount = User::firstOrCreate(
[ 'email' => "accreditor@cvsucarmona.com" ],
[
'name' => "Accreditor",
'nonofficial_category_id' => 0,
'role' => "accreditor",
'email' => "accreditor@cvsucarmona.com",
'password' => Hash::make('accreditor_cvsucarmona'),
'email_verified_at' => now()
]
);
为了解释为什么你会得到你的错误,该firstOrCreate()
方法是检查['name' => "Accreditor"]
它是否是唯一的,然后尝试插入['nonofficial_category_id' => 0],
只有nonofficial_category_id
列设置的,因此抱怨角色没有默认值,ergo,你需要提供一个值。
推荐阅读
- python-3.x - 在 Python 中通过 selenium-chromedriver 提交表单时出现问题
- oracle - Oracle - 根据组间距创建组
- querydsl - 在 QueryDsl 中编写条件查询
- html - 哪个modelfield可以在django中存储视频播放时间?或者,显示没有关联时钟的 TimeField
- javascript - VueJS Method Not Being Called on Async Fuction Callback
- sql - SQL Server 存储过程性能问题 - WHILE EXISTS
- c - 当 char 数组转换为 long double 时得到错误的值
- vue.js - 每次编译我的应用程序时都必须创建一个 .nuxt 文件夹
- c# - 可以将 C# 应用程序下载到 Web 浏览器并纯粹在用户的计算机上运行吗?
- javascript - 将函数内部的变量传递给其他函数而不更改其在 Javascript 中的值