Laravel-1215无法添加外部约束



我试图将最多三个表链接在一起,但当我运行迁移(使用artisan(时,我不断收到错误:

一般错误:1215无法添加外键约束(SQL:更改表stores添加约束stores_sale_id_foreign外键(sale_id(引用bikes(id((

这是我的商店迁移文件:

class CreateStoresTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('stores', function (Blueprint $table) {
$table->increments('id');
$table->string('store_name');
$table->string('city');
$table->string('manager');
$table->integer('sale_id')->unsigned();
$table->timestamps();
});
Schema::table('stores', function ($table){
$table->foreign('sale_id')->references('id')->on('bikes');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down() {
Schema::dropIfExists('stores');
}
}

商店型号:

class Store extends Model {
use HasFactory;
protected $table = 'stores';
protected $fillable = ['store_name', 'city', 'manager', 'sale_id'];
}

编辑:自行车迁移:

use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;
class CreateBikesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('bikes', function (Blueprint $table) {
$table->increments('id');
$table->string('make');
$table->string('model');
$table->string('category');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('bikes');
}
}

对于两个表,请尝试$table->id()$table->bigIncrements('id'),而不是增量。因为id列将具有正确的类型。

您还需要将外键列设置为$table->unsignedBigInteger('sale_id');,以便在外部约束之前设置正确的列类型。

你必须确保你的自行车迁移在你的商店迁移之前进行。

试试这个,

class CreateStoresTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('stores', function (Blueprint $table) {
$table->increments('id');
$table->string('store_name');
$table->string('city');
$table->string('manager');
$table->integer('sale_id')->unsigned()->nullable();
$table->timestamps();
$table->foreign('sale_id')->references('id')->on('bikes')->onDelete('cascade')->onUpdate('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down() {
Schema::dropIfExists('stores');
}
}

使用此代码

class CreateStoresTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('stores', function (Blueprint $table) {
$table->increments('id');
$table->string('store_name');
$table->string('city');
$table->string('manager');
$table->unsignedInteger('sale_id')->nullable();
$table->foreign('sale_id')->references('id')->on('bikes')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down() {
Schema::dropIfExists('stores');
}
}

注意:请确保外键字段类型不匹配。

  • 将原始迁移从increments((更改为justbigIncrements((
  • 或者在外键列中执行unsignedBigInteger((,而不是unsignedInteger(

最新更新