首页 > 解决方案 > 数据库播种器和 Laravel 的问题

问题描述

我有 3 个表,架构如下。雇员,

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),

员工迁移表:

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

部门 部门DB.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();
    });

薪水

工资数据库.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.
    ];
});

工资移民

$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 类 Department 扩展 Model

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

应用\员工

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

应用\工资

    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`))")

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

这是为了以后:部门不能在自己的表中重复。IE。一旦创建了带有名称的部门 id,就不能再次重新创建它。

我知道我错了,否则不会有错误。当我为部门和工资运行 dbSeeder 时,它运行良好。但是,只要有重复的部门条目,它就会引发错误。但是存储在数据库中的数据很好。

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

谢谢!

编辑 当我执行 php artisan migrate

迁移顺序

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)

标签: laravelfaker

解决方案


只需更改迁移的顺序。我猜你正试图在创建表之前建立关系。进行父表的第一次迁移


推荐阅读