Laravel Seeder-如何在唯一列上播种空值

时间:2018-10-18 06:45:52

标签: laravel

我有简单的用户模型:

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('email')->unique();
    $table->string('password');
    ...
}

我想制作一个不会填充用户以后可能会填充的电子邮件地址的播种器:

for($i = 0; $i < 11; $i++){
    $user = new User();
    $user->save();
}

但是我有一个明显的错误:

  

SQLSTATE [HY000]:常规错误:1364字段'email'没有默认值

我尝试为播种机使用User Model mutator:

用户模型

public function setEmailAttribute($value) {
    if ( empty($value) ) { // will check for empty string
        $this->attributes['email'] = NULL;
    } else {
        $this->attributes['email'] = $value;
    }
}

用户种子

for($i = 0; $i < 11; $i++){
    $user = new User();
    $user->setEmailAttribute('');
    $user->app_role = "user";
    $user->save();
}

但这在这里对我不起作用,我再次遇到错误:

  

SQLSTATE [23000]:违反完整性约束:1048列'email'不能为空

但是,我不想将email列永久设置为uniquenullable,因为我只想对播种机进行测试。

有人知道如何在这里找到解决方案吗?

1 个答案:

答案 0 :(得分:2)

在迁移的nullable()列中添加email

    $table->string('email')->unique()->nullable()

然后在命令行中运行以下命令

1。composer dump-autoload //更新迁移中的更改

2。php artisan migrate:fresh --seed //新的迁移并为您的播种者播种