I have a project named Partner
I need to create developers
table and two other tables branches
and projects
And every Developer has many branches and has many projects
So I created this migration files:
Developers
public function up()
{
Schema::create('developers', function (Blueprint $table) {
$table->id();
$table->string('company_name', 100);
$table->string('responsible_name', 100);
$table->string('email', 100);
$table->string('phone', 100);
$table->string('hotline', 100)->nullable();
$table->timestamps();
});
}
Branches
public function up()
{
Schema::create('branches', function (Blueprint $table) {
$table->id();
$table->integer('developer_id')->unsigned();
$table->string('name', 100);
$table->string('address', 100);
$table->string('location', 100);
$table->string('phone', 100);
$table->timestamps();
$table->foreign('developer_id')->references('id')->on('developers')->onDelete('cascade');
});
}
Projects
public function up()
{
Schema::create('projects', function (Blueprint $table) {
$table->id();
$table->integer('developer_id')->unsigned();
$table->string('name', 100);
$table->string('type', 100);
$table->string('address', 100);
$table->string('location', 100);
$table->string('availability', 100);
$table->text('payment_plan');
$table->string('brochure', 100)->nullable();
$table->timestamps();
$table->foreign('developer_id')->references('id')->on('developers')->onDelete('cascade');
});
}
But when I ran php artisan migrate
I got this error
SQLSTATE[HY000]: General error: 1005 Can't create table `partner`.`branches` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `branches` add constraint `branches_developer_id_foreign` foreign key (`developer_id`) references `developers` (`id`) on delete cascade)
What is the wrong with the form of the foreign key?
CodePudding user response:
You can use foreign key in migration without predefine field :
$table->foreignId('developer_id')->constrained('developers')->onDelete('cascade');
and remove this line :
$table->integer('developer_id')->unsigned();