我猜想的常見問題,但我無法解決它,儘管我在網上找到的信息。雄辯 - 無法添加外鍵約束
我有關係的hasMany的序列:
- 用戶有許多客戶有許多合同有許多材料。
我做了我最好的,但我發現自己面對這個錯誤:
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: create tableclients
(id
int unsigned not null,user_id
int unsigne d null, ...) default character set utf8mb4 collate
utf8mb4_unicode_ci engine = InnoDB)SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
遷移:
class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->engine = 'InnoDB';
// Keys
$table->increments('id');
// Other
...
$table->timestamps();
});
}
public function down()
{
Schema::disableForeignKeyConstraints();
Schema::dropIfExists('clients');
Schema::drop('users');
Schema::enableForeignKeyConstraints();
}
}
class CreateClientsTable extends Migration
{
public function up()
{
Schema::create('clients', function (Blueprint $table) {
$table->engine = 'InnoDB';
// keys
$table->unsignedInteger('id')->unique();
$table->primary('id');
$table->unsignedInteger('user_id')
->nullable();
$table->foreign('user_id')->references('id')->on('users')
->onDelete('cascade');
// others
...
});
}
public function down()
{
Schema::disableForeignKeyConstraints();
Schema::dropIfExists('contracts');
Schema::drop('clients');
Schema::enableForeignKeyConstraints();
}
}
class CreateContractsTable extends Migration
{
public function up()
{
Schema::create('contracts', function (Blueprint $table) {
$table->engine = 'InnoDB';
// Keys
$table->increments('id');
$table->string('contract_number')->unique();
$table->unsignedInteger('client_id');
$table->foreign('client_id')->references('id')->on('clients')
->onDelete('cascade');
// Others
...
});
}
public function down()
{
Schema::disableForeignKeyConstraints();
Schema::dropIfExists('materials');
Schema::drop('contracts');
Schema::enableForeignKeyConstraints();
}
}
class CreateMaterialsTable extends Migration
{
public function up()
{
Schema::create('materials', function (Blueprint $table) {
$table->engine = 'InnoDB';
// Keys
$table->increments('id');
$table->string('contract_number')->unique();
$table->unsignedInteger('contract_id');
$table->foreign('contract_id')->references('id')->on('contracts')
->onDelete('cascade');
// Others
...
});
}
public function down()
{
Schema::drop('materials');
}
}
我在做什麼錯?
你使用的是mysql/mariadb嗎?如果是,什麼版本? – Jerodev
你的列是同一種數據類型嗎? –
我正在使用mysql,是的他們是... – Pixeuh