Schema::create('students', function (Blueprint $table) {
$table->id();
$table->integer('age')->unsigned();
$table->integer('city_id')->unsigned();
$table->foreign('city_id')->references('id')->on('cities')->onDelete('cascade');
$table->timestamps();
});
Schema::create('cities', function (Blueprint $table) {
$table->id();
$table->text('name');
$table->timestamps();
});
我是新的 laravel,當我在終端秀中運行遷移時
SQLSTATE [HY000]:一般錯誤:1215 無法添加外鍵約束(SQL:洗掉級聯時更改表students添加約束students_city_id_foreign外鍵(city_id)參考cities( ))id
幫我修
uj5u.com熱心網友回復:
您的問題出在代碼順序上。您想為尚不存在的表創建外鍵。
試試這個:
Schema::create('students', function (Blueprint $table) {
$table->id();
$table->integer('age')->unsigned();
$table->integer('city_id')->unsigned();
$table->timestamps();
});
Schema::create('cities', function (Blueprint $table) {
$table->id();
$table->text('name');
$table->timestamps();
});
Schema::table('students', function(Blueprint $table) {
$table->foreign('city_id')->references('id')->on('cities')->onDelete('cascade');
});
像這樣,您首先創建兩個表,然后設定外鍵。
uj5u.com熱心網友回復:
如果你正在使用更新版本的 Laravelid欄位,現在是unsignedBigInteger欄位。因此,您應該執行以下操作:
Schema::create('cities', function (Blueprint $table) {
$table->id();
$table->text('name');
$table->timestamps();
});
Schema::create('students', function (Blueprint $table) {
$table->id();
$table->integer('age')->unsigned();
$table->foreignId('city_id')->constrained()->onDelete('cascade');
$table->timestamps();
});
此外,請確保城市遷移在學生之前進行。
uj5u.com熱心網友回復:
=>your cities migration first create then after students migration create because your city_id foreign key reference to the cities table laravel migration check order and order wise migration run so first cities migration run(cities table create) then students migration run.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/422358.html
標籤:
