laravel seeds唯一列忽略重复条目

问题描述 投票:0回答:4

我在Laravel有一台播种机

public function run()
    {
        $user = App\Admin::create([

            'first_name'     => 'first',
            'last_name'    => 'last',
            'phone'    => '',
            'email'    => '[email protected]',
        ]);
    }

在这封电子邮件中是独特的

php artisan db:seed

当我第一次运行其输入记录到数据库时,当我再次运行它显示重复的条目。

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '[email protected]' for key 'email'

我可以选择忽略它吗?

php laravel laravel-5
4个回答
1
投票

在每次运行之前尝试刷新数据库。导入:

使用Illuminate \ Foundation \ Testing \ RefreshDatabase;

...并将其放在班级的顶部:

使用RefreshDatabase;

(来自:https://laravel.com/docs/5.8/database-testing#resetting-the-database-after-each-test


0
投票

我们可以选择检查表中是否存在给定的电子邮件。

public function run(){
            $admin = DB::table('admins')->where('email', '=', '[email protected]')->first();

            if ($admin === null) {
                // user doesn't exist
                $user = App\Admin::create([

                    'first_name'     => 'Walter',
                    'last_name'    => 'Brown',
                    'phone'    => '',
                    'email'    => '[email protected]',
                    'password' => Hash::make('Admin123'),
                    'is_active'    => 1,
                    'remember_token' => str_random(10)
                ]);
             }
        }

-1
投票

你可以通过两种方式解决它:

1)从数据库中的电子邮件列中删除唯一键约束(不推荐)

2)使用faker库生成唯一的电子邮件地址 - https://github.com/fzaninotto/Faker


-1
投票

填充数据库的简单方法是创建工厂,然后使用该工厂运行播种机。

创建工厂,通常在数据/工厂目录中:

$factory->define(App\Admin::class, function (Faker\Generator $faker) {
    return [
        'first_name'    => $faker->firstName,
        'last_name'     => $faker->lastName,
        'phone'         => $faker->phoneNumber,
        'email'         => $faker->email
    ];
});

然后运行你的播种机:

factory(Admin::class, 20)->create();

此示例将创建20个用户并存储它们。

上面的示例使用Faker生成随机数据https://github.com/fzaninotto/Faker

© www.soinside.com 2019 - 2024. All rights reserved.