2014-03-24 62 views
0

我一直在这里寻找答案,但似乎没有任何工作。我已经完成了Laravel和Sentry 2的基本安装。首先,我已经添加了此迁移,以将user_id列添加到users表中。Laravel迁移的外键问题

Schema::table('users', function(Blueprint $table) 
    { 
     $table->integer('client_id')->unique; 
    }); 

然后,接下来我创建了我的客户端表,并在不同的迁移中使用以下内容。

Schema::create('clients', function(Blueprint $table) 
    { 
     $table->increments('id'); 
     $table->timestamps(); 
     $table->integer('client_id')->unique; 
     $table->string('client_name'); 
     $table->date('expiry'); 
     $table->integer('cals'); 
    }); 

最后我创建在以下迁移

Schema::table('users', function(Blueprint $table) 
    { 
     $table->foreign('client_id') 
      ->references('client_id')->on('clients') 
      ->onDelete('cascade'); 
    }); 

误差即时得到如下。

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `users` add constraint use 
rs_client_id_foreign foreign key (`client_id`) references `clients` (`client_id`) on delete cascade) 

我有点卡在我应该找的东西,他们都应该是索引?

+0

当您手动运行它们(即使用MySQL客户端或phpmyadmin)时,这些查询是否工作? – Kryten

+0

在phpmyadmin中说没有定义索引。 – Nathan

回答

0
$table->integer('client_id')->unique; 

此行应为:

$table->integer('client_id')->unique(); 

无论如何,如果你实际上是试图用一个外键约束引用的“ID”栏上的“客户”表上的“用户”表,然后执行以下操作:

Schema::table('users', function(Blueprint $table) 
{ 
    $table->integer('client_id')->unsigned(); 

    $table->foreign('client_id') 
     ->references('id')->on('clients') 
     ->onDelete('cascade'); 
}); 

Schema::create('clients', function(Blueprint $table) 
{ 
    $table->increments('id'); 
    $table->timestamps(); 
    $table->string('client_name'); 
    $table->date('expiry'); 
    $table->integer('cals'); 
}); 
+0

这是唯一的位,我不知道我错过了它。第二位实际上是否工作正如你试图为存在的表创建约束? (当你之后创建它) – Nathan

+0

是的,第二位应该工作。无论表是否存在,我总是为每个表创建一个迁移,并在该迁移中包含任何外键约束。 – seeARMS