我正在尝试使用laravel创建主键-外键关系,但我一直收到此错误
SQLSTATE[HY000]: General error: 1005 Can't create table `volga_2`.`employees` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `employees` add constraint `employees_dept_id_foreign` foreign key (`dept_id`) references `departments` (`id`))
我似乎无法找出问题出在哪里,因为在查看了SO的其他答案之后,我对模式进行了更改。
当我运行php artisan migrate
时,会弹出上述错误,并且会部分迁移。
任何指向这的指针都很棒,因为我一直在寻找解决方案!
谢谢!
员工表
Schema::create('employees', function (Blueprint $table) {
$table->bigIncrements('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('salary');
$table->string('name');
$table->string('gender');
$table->timestamp('date_of_joining');
$table->dateTime('date_of_birth');
$table->timestamps();
部门表
Schema::create('departments', function (Blueprint $table) {
$table->increments('id');
$table->string('dept_name');
$table->timestamps();
工资表
Schema::create('salaries', function (Blueprint $table) {
$table->increments('id');
$table->string('monthlySalary');
$table->timestamps();
已添加: DB Seeder。
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);
});
根据评论更改了数据库种子
factory(App\Department::class, 10)->create()->each(function ($department) {
$salary = factory(App\Salary::class)->make();
$department->salary()->save($salary);
$employee = factory(App\Employee::class)->make();
$salary->employee->save($employee);
});
答案 0 :(得分:0)
请确保您在employees
迁移中引用的表已经存在,以便可以对其进行实际引用。您可以通过重命名文件或更改employees
迁移的文件名中的日期部分来完成departments
和salaries
迁移之后的操作。
您还需要更改
$table->foreign('salary_id')->references('id')->on('salary');
到
$table->foreign('salary_id')->references('id')->on('salaries');
以反映您在salaries
迁移中使用的同一表名。
https://laravel.com/docs/5.8/migrations#foreign-key-constraints