我的 laravel 應用程式中有兩個表。
公司表員工表。
以下是我的公司表遷移檔案。
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('companies', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('logo');
$table->text('email', 50)->unique();
$table->string('website');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('companies');
}
};
以下是員工表。
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('employees', function (Blueprint $table) {
$table->id();
$table->string('first_name');
$table->string('last_name');
$table->text('email', 50)->unique();
$table->text('phone', 50)->unique();
$table->integer('company_id')->unsigned();
$table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('employees');
}
};
但,
每當我嘗試運行員工表遷移時,它總是給我一個錯誤說,
SQLSTATE[HY000]:一般錯誤:1005 無法創建表
laraapp。employees(errno: 150 "Foreign key constraint is wrongly forms") (SQL: alter tableemployeesadd constraintemployees_company_id_foreignforeign key (company_id) referencescompanies(id) on delete cascade)
我公司表的 ID 是未簽名的。
uj5u.com熱心網友回復:
的值$table->id();實際上是unsignedBigInteger(),但您已將company_id外鍵列定義為僅是,unsignedInteger因此兩種列型別不匹配。
當您使用 Laravel 9 時,您可以使用foreignId()自動創建具有正確型別的列的方法:
$table->foreignId('company_id');
您也可以使用該foreignIdFor()方法,該方法也將創建基本所需的fk約束,因此您不必這樣做。
$table->foreignIdFor(Company::class);
為了完整性:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('employees', function (Blueprint $table) {
$table->id();
$table->string('first_name');
$table->string('last_name');
$table->text('email', 50)->unique();
$table->text('phone', 50)->unique();
$table->foreignIdFor(Company::class);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('employees');
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/514643.html
上一篇:Laravel-嵌套關系
