Laravel迁移不会添加外键

arr*_*l12 6 php laravel

我是迁移的新手,并试图创建两个带有外键的表,其中一个引用另一个中的id,但是我一般都无法添加键错误.有什么我想念的吗?

错误:

[PDOException] SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

码:

    Schema::create('app_groups', function($table) {
     $table->increments('id');
     $table->string('app_name');
     $table->unsignedInteger('app_group_id');
     $table->timestamps();
  });

  Schema::create('app_to_bucket', function($table) {
     $table->increments('id');
     $table->unsignedInteger('app_group_id');
     $table->unsignedInteger('bucket_id');
     $table->timestamps();
  });
  Schema::table('app_to_bucket', function($table) {
     $table->foreign('app_group_id')->references('app_group_id')->on('app_groups')->onDelete('cascade');
  });
Run Code Online (Sandbox Code Playgroud)

Tod*_*rov 19

这肯定会起作用.Eloquent主键是整数,长度为10,无符号.这就是这种关系不起作用的原因.

Schema::create('app_groups', function($table) {
     $table->string('app_name');
     $table->integer('app_group_id')->length(10)->unsigned();
     $table->timestamps();
  });

  Schema::create('app_to_bucket', function($table) {
     $table->integer('app_group_id');
     $table->integer('bucket_id')->length(10)->unsigned();
     $table->timestamps();
  });
  Schema::table('app_to_bucket', function($table) {
     $table->foreign('app_group_id')->references('app_group_id')->on('app_groups')->onDelete('cascade');
Run Code Online (Sandbox Code Playgroud)

  • 工作完美,谢谢.看起来更加谨慎,文档说:"注意:当创建引用递增整数的外键时,请记住始终使外键列无符号." (参考:http://laravel.com/docs/schema) (3认同)

arr*_*l12 7

我已经解决了这个问题.

问题是Laravel自动假定将列递增为主键.所以我需要指明我app_group_id是主键.

 Schema::create('app_groups', function($table) {
     $table->string('app_name');
     $table->integer('app_group_id');
     $table->primary('app_group_id');
     $table->timestamps();
  });

  Schema::create('app_to_bucket', function($table) {
     $table->integer('app_group_id');
     $table->integer('bucket_id');
      $table->primary('bucket_id');
     $table->timestamps();
  });
  Schema::table('app_to_bucket', function($table) {
     $table->foreign('app_group_id')->references('app_group_id')->on('app_groups')->onDelete('cascade');
  });
Run Code Online (Sandbox Code Playgroud)