【发布时间】:2020-04-04 11:37:11
【问题描述】:
我正在尝试在 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();
添加: 数据库播种机。
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);
});
根据评论更改了 DB Seeder
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);
});
【问题讨论】:
标签: laravel-5 eloquent foreign-keys migration