php - 1215 一般错误:无法添加外键约束 Laravel
问题描述
我有一个已经创建外键约束的表:
错误:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key
constraint (SQL: alter table `league_seasons` add
constraint `league_seasons_league_id_foreign` foreign key (`league_id`)
references `leagues` (`id`) on delete cascade)
这是排行榜
public function up() {
Schema::create('leagues', function (Blueprint $table) {
$table->integer('id');
$table->increments('increment_id');
$table->string('type')->nullable();
$table->integer('legacy_id')->nullable();
$table->integer('country_id')->nullable();
}
这是league_seasons 表
public function up() {
Schema::create('league_seasons', function (Blueprint $table) {
$table->integer('id');
$table->increments('increment_id');
$table->string('name')->nullable();
$table->unsignedInteger('league_id');
$table->string('is_current_season')->nullable();
$table->string('current_round_id')->nullable();
$table->string('current_stage_id')->nullable();
App\Helpers\DbExtender::defaultParams($table, true);
});
Schema::table('league_seasons', function (Blueprint $table) {
$table->foreign('league_id')->references('id')->on('leagues')->onDelete('cascade');
});
}
我试过交换 unSignedInteger、BigInteger 但它们似乎都没有工作。知道为什么会这样吗?谢谢
解决方案
As @repat pointed out, adding unSignedInteger with index() on both table worked for me.
final league table:
public function up() {
Schema::create('leagues', function (Blueprint $table) {
$table->unsignedInteger('id')->index();
$table->increments('increment_id');
$table->string('type')->nullable();
$table->integer('legacy_id')->nullable();
$table->integer('country_id')->nullable();
$table->string('name')->nullable();
}
final league_seasons table:
public function up() {
Schema::create('league_seasons', function (Blueprint $table) {
$table->integer('id');
$table->increments('increment_id');
$table->string('name')->nullable();
$table->unsignedInteger('league_id')->index();
$table->string('is_current_season')->nullable();
$table->string('current_round_id')->nullable();
$table->string('current_stage_id')->nullable();
App\Helpers\DbExtender::defaultParams($table, true);
});
Schema::table('league_seasons', function (Blueprint $table) {
$table->foreign('league_id')->references('id')->on('leagues')->onDelete('cascade');
});
}
推荐阅读
- chapel - Multilocale Chapel:检查失败(GASNet:无效的节点数:-nl)
- javascript - 有没有办法在没有 HTML 的情况下在控制台中请求用户输入(在 ES6 中)?
- graphql - 运行 GraphQL 查询返回 ID `1` 的格式无效
- python - 控制 API:服务不可用 (503)
- php - Wordpress 循环:自定义帖子数量并按日期排序
- ninja - 使用介子和忍者安装 DPDK
- database - mongod.service active : 失败(无法启动 mongodb 服务器)
- json - 如何为 Flutter 解析这种类型的 JSON?
- delphi - 如何将 ' 字符添加到 TINiFile 中的键和值
- or-tools - 使用ortools时如何获取cpsolver的变量和约束