Laravel 1215无法添加外键约束

时间:2017-04-11 09:51:01

标签: php mysql database laravel

您好我的laravel应用程序中的数据库迁移有问题

这是错误:

[Illuminate\Database\QueryException]                                         
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL  
  : alter table `transactions` add constraint `transactions_user_sid_foreign`  
   foreign key (`user_sid`) references `users` (`sid`))

这是我的交易迁移:

public function up()
    {
        Schema::create('transactions', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('user_sid')->index();
            $table->unsignedInteger('store_id')->index();
            $table->unsignedInteger('value');
            $table->timestamps();
            $table->softDeletes();
        });
    }

这是用户迁移:

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->unsignedInteger('role_id')->index();
            $table->string('sid')->unique();
            $table->rememberToken();
            $table->timestamps();
            $table->softDeletes();
        });
    }

最后是我的外键:

Schema::table('transactions', function (Blueprint $table){
            $table->foreign('user_sid')->references('sid')->on('users');
            $table->foreign('store_id')->references('id')->on('stores');
        });

1 个答案:

答案 0 :(得分:4)

您无法将外键添加到具有不同类型的列中,因此只需更改它,例如在users表中:

$table->unsignedInteger('sid')->unique();