繁体   English   中英

Laravel 8 firstOrCreate 无法使用 $fillable

[英]Laravel 8 firstOrCreate Not Working With $fillable

我的 controller 中有此代码:

$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))

在错误显示中,似乎列roleemailpassword没有填写我的记录。 我很确定我已将这些列包含在我的$fillable中。

下面是我的User model:

<?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,您需要提供一个值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM