gpt4 book ai didi

php - laravel seeds 唯一列忽略重复条目

转载 作者:行者123 更新时间:2023-12-03 08:55:53 27 4
gpt4 key购买 nike

我在 Laravel 中有一个 Seeder

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

'first_name' => 'first',
'last_name' => 'last',
'phone' => '',
'email' => '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a8c5c9c1c4e8cfc5c9c1c486cbc7c5" rel="noreferrer noopener nofollow">[email protected]</a>',
]);
}

这封电子邮件是独一无二的,

php artisan db:seed

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

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="472a262e2b07202a262e2b6924282a" rel="noreferrer noopener nofollow">[email protected]</a>' for key 'email'

我可以选择忽略它吗?

最佳答案

您可以在模型上使用 firstOrCreate() 方法,如下所示:

public function run()
{
App\Admin::firstOrCreate([

'first_name' => 'first',
'last_name' => 'last',
'phone' => '',
'email' => '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e28f838b8ea2858f838b8ecc818d8f" rel="noreferrer noopener nofollow">[email protected]</a>',
]);
}

如果您想插入多条记录,您可以在 run() 函数中执行以下操作:

$records = [
[
'first_name' => 'first',
'last_name' => 'last',
'phone' => '',
'email' => '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aac7cbc3c6eacdc7cbc3c684c9c5c7" rel="noreferrer noopener nofollow">[email protected]</a>',
],
[
'first_name' => 'first2',
'last_name' => 'last2',
'phone' => '',
'email' => '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9bf6faf2f7a9dbfcf6faf2f7b5f8f4f6" rel="noreferrer noopener nofollow">[email protected]</a>',
]
];

foreach($records as $record) {
App\Admin::firstOrCreate($record);
}

每当我想确保数据库中不插入重复值时,我都会在播种器中使用此技巧。 firstOrCreate() 方法会检查记录是否在数据库中,如果不在则创建。

关于php - laravel seeds 唯一列忽略重复条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55475389/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com