0

以下是我的迁移

迁移

users 表与 customer 表有关系

在用户中:

$table->integer('customer_id')->unsigned();
$table->foreign('customer_id')->references('id')->on('customers');

当我打电话时php artisan migrate:refresh --seed,工匠给了我以下错误:

[Illuminate\Database\QueryException]                                         
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL  
  : alter table `users` add constraint `users_customer_id_foreign` foreign ke  
  y (`customer_id`) references `customers` (`id`))                             



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

因为客户表不存在......(很明显)

有没有办法解决这个问题?我知道更改文件的日期会解决这个问题,但应该有更好的方法

4

3 回答 3

2

在添加外键之前,您必须创建要引用的表。一个解决方案是从您的用户表迁移中删除外键约束并创建一个添加外键约束的新迁移。

于 2017-02-20T09:03:16.870 回答
0

试着分开做。

public function up()
{
    Schema::create('users', function(Blueprint $table) {
        $table->increments('id');
        $table->integer('costumer_id')->unsigned();
        $table->string('email')->unique();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });

   Schema::table('users', function($table) {
       $table->foreign('costumer_id')->references('id')->on('costumers');
   });
}

您可以尝试的另一件事(自 laravel 5.3 起):

unsignedInteger('column_name') instead of ('column_name')-unsigned()
于 2017-02-20T09:00:52.847 回答
0

如果您将一个字段设置为“无符号”,而另一个则没有。一旦您将两列都设置为无符号,它就可以工作。

于 2017-02-20T09:13:38.220 回答