PHP工匠循环数组错误

时间:2017-11-06 05:38:17

标签: php mysql arrays laravel artisan

我正在尝试将一些数据导入mySql数据库。第一行被添加,但其他人不。基本上它没有循环,所以它显示错误说:

  

[Illuminate \ Database \ QueryException] SQLSTATE [23000]:完整性   约束违规:1062重复条目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,如下所示,&#34; AA&#34;,&#34; a&#34;更新到数据库。但是,它不会更新&#34; BB&#34;,&#34; B&#34;并尝试更新&#34; AA&#34;,&#34; a&#34;试。

<?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]未定义的偏移量:0

1 个答案:

答案 0 :(得分: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 );
            }

        }
    }
?>