2017-05-30 109 views
-1

时尝试使用laravel迁移为什么发生这个错误

像这样的例子,当使外键:

用户表

public function up() 
{ 
    Schema::create('flights', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->string('name'); 
     $table->TinyInteger('color_id')->unsigned(); 
     $table->foreign('color_id')->references('id')->on('colors'); 
     $table->timestamps(); 
    }); 
} 

色表

public function up() 
{ 
    Schema::create('flights', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->string('color'); 
     $table->timestamps(); 
    }); 
} 

有时属性不起作用

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

回答

0

发生这种错误,因为外键[用户表(类型)是从在[颜色表]主键(类型)输精管

为了解决这个问题应该改变[颜色表]中的主键

$table->tinyIncrements('id');


当您使用主键$table->Increments('id');

你应该使用Integer作为一个外键

$table-> unsignedInteger('fk_id'); 
    $table->foreign('fk_id')->references('id')->on('table_name'); 

当您使用主键$table->tinyIncrements('id');

当您使用主键$table->smallIncrements('id');

你应该使用 unsignedTinyInteger作为一个外键

$table-> unsignedTinyInteger('fk_id'); 
    $table->foreign('fk_id')->references('id')->on('table_name'); 

当您使用主键$table->mediumIncrements('id');

你应该使用unsignedMediumInteger作为一个外键

$table-> unsignedMediumInteger('fk_id'); 
    $table->foreign('fk_id')->references('id')->on('table_name'); 
你应该使用 unsignedSmallInteger作为一个外键

$table-> unsignedSmallInteger('fk_id'); 
    $table->foreign('fk_id')->references('id')->on('table_name'); 

0

为了外键约束的工作,除了具有相同的列类型,父列也应(或形式)主键或上应该有一个index。阅读文档here

的InnoDB允许外键引用 列的任一列或组。但是,在参考表中,必须有一个索引 ,其中被引用的列被列为 相同顺序中的第一列。

在你的情况下,它可能没有索引,因此它失败。

相关问题