gpt4 book ai didi

PHP artisan循环数组错误

转载 作者:行者123 更新时间:2023-11-29 18:14:34 25 4
gpt4 key购买 nike

我正在尝试将一些数据放入 mySql 数据库中。第一行被添加,但其他行没有添加。基本上它不会循环,因此显示错误:

[Illuminate\Database\QueryException] SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry xxxxx

<?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;

class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$this->call(xSeeder::class);
$this->call(xxSeeder::class);

Artisan::call('cache:clear', []);
}
}

它运行如下所示的 xSeeder,并且“AA”、“a”被更新到数据库中。但是,它不会更新“BB”、“B”,而是尝试再次更新“AA”、“a”。

<?php
use App\Role;
use App\Permission;
use Illuminate\Database\Seeder;

class DepartmentSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{

/** @var Roles */
$default_role_list = [
['display_name' => 'AA', 'name' => 'a'],
['display_name' => 'BB', 'name' => 'b'],
['display_name' => 'CC', 'name' => 'c'],

];

foreach ($default_role_list as $role) {
Role::create([
'name' => $role['name'],
'display_name' => $role['display_name'],
]);
}

}
}

我尝试了另一个代码:

<?php
use App\Role;
use App\Permission;
use Illuminate\Database\Seeder;
class DepartmentSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{

/** @var Roles */
$default_role_list = array(
0 => array("display_name"=>"AA","name"=>"a"),
1 => array("display_name"=>"BB","name"=>"b"),
2 => array("display_name"=>"CC","name"=>"c"),
);
$default_role_list_count =0;
foreach ($default_role_list as $role) {
Role::create( array(
'name' => $role[$default_role_list_count]['name'],
'display_name' => $role[$default_role_list_count]['display_name'],
));
$default_role_list_count++;
}

}
}?>

这显示错误:

[ErrorException] Undefined offset: 0

最佳答案

您可以使用此代码

    <?php
use App\Role;
use App\Permission;
use Illuminate\Database\Seeder;
class DepartmentSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{

/** @var Roles */
$default_role_list = array(
array("display_name"=>"AA","name"=>"a"),
array("display_name"=>"BB","name"=>"b"),
array("display_name"=>"CC","name"=>"c"),
);
foreach ($default_role_list as $role) {
Role::create( $role );
}

}
}
?>

关于PHP artisan循环数组错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47130394/

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