I have a problem
to make migration with relationship.
case :
- 1 Department will have many Employees
- 1 Employee belongTo 1 Department
- 1 Department will have one manager (from employees table)
Here is my migration
Schema::create('departments', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->foreignId('manager_id')->nullable()
->references('id')->on('employees')
->nullOnDelete();
$table->timestamps();
});
Schema::create('employees', function (Blueprint $table) {
$table->id();
$table->string('name', 255)->nullable();
$table->string('picture', 1024)->nullable();
$table->foreignId('user_id')->nullable()
->references('id')->on('users')
->nullOnDelete();
$table->foreignId('department_id')->nullable()
->references('id')->on('departments')
->nullOnDelete();
$table->timestamps();
});
when I do php artisan migrate:fresh
it show up error :
SQLSTATE[42000]: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Foreign key
'departments_manager_id_foreign' references invalid table 'employees'.
(SQL: alter table "departments" add constraint "departments_manager_id_foreign" foreign key ("manager_id")
references "employees" ("id") on delete set null)
This because there is no employees table when trying to create departments.
But if I trying to create employees first, then no departments tables.
Any suggestion for my problem ?
Thank you
2
Answers
this should work
as @TimLewis suggested in the comment, you can add the department table without foreign key first, then add the employees table and setup the foreign key for the departments table.
Department migration
The employees migration