数据库播种器和 Laravel 的问题

Issues with Database Seeder and Laravel

我有 3 个 table,架构如下。 员工,

EmployeeDB.php

$factory->define(Employee::class, function (Faker $faker) {
    return [
        'emp_id' => $faker->randomDigit,
        'name' => $faker->name,
        'dept_id' => $faker->numberBetween($min = 1, $max = 15),
        'salary_id' => $faker->randomDigit(),
        'gender' => $faker->randomElement(['M', 'F', 'T']),
       /*if I remove these next 2 statements, I receive an error for 
       SQLSTATE[42S22]: Column not found: 1054 Unknown column 
       'employee_id' in 'field list' (SQL: insert into `employees` (`emp_id`, `name`, `dept_id`, `salary_id`, `gender`, `date_of_joining`,
        `date_of_birth`, `employee_id`, `updated_at`, `created_at`) values (2, Jamaal Beer, 3, 9, T, 2018-05-05 18:59:40, 2005-07-05 13:17:23, ?, 
        2019-12-11 11:15:42, 2019-12-11 11:15:42))
       */ 
       'employee_id' => $faker->randomDigit,
       //Same for this one as well
        'department_id' => $faker->randomDigit,
        'date_of_joining' => $faker->dateTimeBetween($startDate = '-5 years', $endDate = 'now', $timezone = null),
        'date_of_birth' => $faker->dateTimeBetween($startDate = '-20 years', $endDate = 'now', $timezone = null),

员工迁移table:

Schema::create('employees', function (Blueprint $table) {
        $table->bigIncrements('emp_id');
        $table->integer('dept_id')->unsigned();
        $table->foreign('dept_id')->references('id')->on('departments');
        $table->integer('salary_id')->unsigned();
        $table->foreign('salary_id')->references('id')->on('salaries');
        $table->string('name');
        $table->string('gender');
        $table->timestamp('date_of_joining');
        $table->dateTime('date_of_birth');
        /*SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'employee_id' cannot be null 
        (SQL: insert into `employees` (`emp_id`, `name`, `dept_id`, `salary_id`, `gender`, `employee_id`, `department_id`, 
        `date_of_joining`, `date_of_birth`, `updated_at`, `created_at`) 
        values (6, Martina Wuckert, 7, 3, F, ?, 3, 2018-09-14 05:59:15, 20
        */
        $table->string('employee_id')->nullable();
        $table->string('department_id')->nullable();
        $table->timestamps();
        //added to prevent errors

部门 DepartmentsDB.php

factory->define(Department::class, function (Faker $faker) {
return [
    //Yes, this is a hack. Use Multidimensional Arrays the next time.
    'id' => $faker->numberBetween($min = 1, $max = 15),
    'dept_name' => $faker->randomElement(['Production', 'Purchase & Quality', 'Operations', 'Sales', 'Customer Serice', 'Business Development', 'Maketing', 'Tech Support', 'Finance', 'Human Resources', 'Research & Development', 'IT', 'Legal']),
];

部门迁移

Schema::create('departments', function (Blueprint $table) {
        $table->increments('id');
        $table->string('dept_name');
        $table->timestamps();
    });

工资

SalaryDb.php

$factory->define(Salary::class, function (Faker $faker) {
    return [
        'id' => $faker->randomDigit(),
        'monthlySalary' => $faker->randomNumber($nbDigits = 3),
        //Yes this is a hack. Use MultiDimensional Arrays the next time.
    ];
});

SalariesMigration

$factory->define(Salary::class, function (Faker $faker) {
    return [
        'id' => $faker->randomDigit(),
        'monthlySalary' => $faker->randomNumber($nbDigits = 3),
        //Yes this is a hack. Use MultiDimensional Arrays the next time.
    ];
});

App\Department class部门扩展模型

{  
    //
    public function employee()
    {
        return $this->hasMany(Employee::class);
    }
    public function salary()
    {
        return $this->hasMany(Salary::class);
    }
}

App\Employee

class Employee extends Model
    {  //belongsto  block
        public function department()
        {
            return $this->hasOne(Department::class);
        }
        public function Salary()
        {
            return $this->hasOne(Salary::class);
        }
    }

App\Salary

    class Salary extends Model
{
    //
    public function employee()
    {
        return $this->belongsTo(Employee::class);
    }
}

DatabaseSeeder.php

 factory(App\Employee::class, 25)->create()->each(function ($employee) {
        $department = factory(App\Department::class)->make();
        $employee->department()->save($department);
        $salary = factory(App\Salary::class)->make();
        $employee->salary()->save($salary);
    });

当我运行下面的命令时,这是我得到的错误 php artisan db:seed

Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`volga_2`.`employees`, CONSTRAINT `employees_dept_id_foreign` FOREIGN KEY (`dept_id`) REFERENCES `departments` (`id`))")

我想做的是:为每个员工记录分配一个部门和一个薪水。

这是为了以后:部门不能在其自己的内部重复 table。 IE。一旦创建了名称为 department id 的 department id,就不能再次创建它。

我知道我走错了,否则不会有错误。当我 运行 部门和薪水的 dbSeeder 时,它工作正常。但是只要有重复的部门条目,它就会抛出一个错误。但是存储在数据库中的数据很好。

我想要一个解决方案或一些指导,因为我还在学习 Laravel。

谢谢!

编辑 当我执行 php artisan 迁移

迁移顺序

Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated:  2014_10_12_000000_create_users_table (0.44 seconds)
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated:  2014_10_12_100000_create_password_resets_table (1.18 seconds)
Migrating: 2019_12_09_105432_create_departments_table
Migrated:  2019_12_09_105432_create_departments_table (0.29 seconds)
Migrating: 2019_12_09_105743_create_salaries_table
Migrated:  2019_12_09_105743_create_salaries_table (0.21 seconds)
Migrating: 2019_12_10_104739_create_employees_table
Migrated:  2019_12_10_104739_create_employees_table (2.04 seconds)

只需更改迁移的顺序即可。我猜你想在 table 创建之前建立关系。进行父级的第一次迁移 table

Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`volga_2`.`employees`, CONSTRAINT `employees_dept_id_foreign` FOREIGN KEY (`dept_id`) REFERENCES `departments` (`id`))")

此错误表示由于某种原因它无法与部门 table 建立关系。在您编写时,您尝试生成 Employee 与其他 2 个 table 的关系,然后再生成它们,通过更改迁移的名称,您可以重新排序迁移。这意味着您可以通过更改迁移名称中的时间来更改 运行 迁移的顺序,以便您按以下顺序迁移:

1) 部门迁移

2) SalariesMigration

3) 员工迁移

感谢大家提供解决方案和思路,帮助我解决这个问题。但是在修补它之后,我制定了一个可以正常工作的解决方案。 我将只发布我所做的更改,以便更容易跟踪,这可能对其他人有帮助。

在这里。

EmployeeDB.php

$factory->define(Employee::class, function (Faker $faker) {
    return [
        'emp_id' => $faker->unique()->randomNumber($nbDigits = 3, $strict = true),
        'name' => $faker->name,
        //dept_id and salary_id pulls the data from their respective tables and then //randomly assigns an id from the id column
        'dept_id' => App\Department::all()->random()->id,
        'salary_id' => App\Salary::all()->random()->id,
        'gender' => $faker->randomElement(['M', 'F', 'T']),
        'date_of_joining' => $faker->dateTimeBetween($startDate = '-5 years', $endDate = 'now', $timezone = null),
        'date_of_birth' => $faker->dateTimeBetween($startDate = '-20 years', $endDate = 'now', $timezone = null),

    ];
});

EmployeeMigration

public function up()
    {
        Schema::create('employees', function (Blueprint $table) {
            $table->unsignedInteger('emp_id', true);
            $table->unsignedInteger('dept_id');
            $table->foreign('dept_id')->references('id')->on('departments');
            $table->unsignedInteger('salary_id');
            $table->foreign('salary_id')->references('id')->on('salaries');
            $table->string('name');
            $table->string('gender');
            $table->timestamp('date_of_joining');
            $table->dateTime('date_of_birth');
            $table->timestamps();
            //added to prevent errors
        });

部门数据库

$factory->define(Department::class, function (Faker $faker) {
    return [
        //Yes, this is a hack. Use Multidimensional Arrays the next time.
        'id' => $faker->unique()->numberBetween(1, 12),
        'dept_name' => $faker->randomElement(['Production', 'Purchase & Quality', 'Operations', 'Sales', 'Customer Serice', 'Business Development', 'Maketing', 'Tech Support', 'Finance', 'Human Resources', 'Research & Development', 'IT', 'Legal']),
    ];
});

部门迁移

 protected $dept_id = 'id';
public function up()
    {

        Schema::create('departments', function (Blueprint $table) {
            $table->unsignedInteger('id', true);
            $table->string('dept_name');
            $table->timestamps();
        });
    }

薪资数据库

$factory->define(Salary::class, function (Faker $faker) {
        return [
            'id' => $faker->unique()->randomNumber($nbDigits = 5, $strict = true),
            'monthlySalary' => $faker->randomNumber($nbDigits = 3),
            //Yes this is a hack. Use MultiDimensional Arrays the next time.
        ];
    });

工资迁移

public function up()
    {
        Schema::create('salaries', function (Blueprint $table) {
            $table->unsignedInteger('id', true);
            $table->string('monthlySalary');
            $table->timestamps();
        });
    }

DatabaseSeeder.php

 public function run()
    {
        $this->call([UsersTableSeeder::class]);//this is not important
        factory('App\Department', 12)->create();
        factory('App\Salary', 50)->create();
        factory('App\Employee', 55)->create();
    }
}

发生的事情是,我首先使用部门 ID 及其各自的名称为部门 table 播种。然后,我用薪水 ID 和薪水金额播种薪水 table。 然后 employees seeder 运行,它通过外键关系引用了部门和薪水 table,并将来自相应 table 中的 id 列的数据插入到 dept_id 和我的员工 table 中的 salary_id 列。

另一个重要方面,设置主键是使用

protected $id = 'Primary Key Table name'

参见上面的 DepartmentMigration 代码块。这需要在 up() 函数的范围之外定义,并且必须存在于需要定义主键的任何地方。

我已经完成了 3 个多小时,计算出每个单独的 DB Seeder,所以我很高兴这个工作。那里可能有更好更优雅的解决方案,但我明天会继续。 :)

感谢您的阅读,希望对您有所帮助。 我将尽我所能回答有关此的任何问题。 :)