无法添加外键约束 - Laravel Entrust

时间:2016-06-20 16:11:29

标签: php mysql laravel foreign-keys entrust

我真的不知道出了什么问题,但我无法在此查询中添加外键约束。

alter table `__acc_role_user` add constraint `__acc_role_user_user_id_foreign` foreign key (`user_id`) references `__acc_accounts` (`account_id`) on delete cascade on update cascade

我如何创建帐户表?

    Schema::create('__acc_accounts', function($table)
    {
        $table->integer('account_id')->increments();
        $table->integer('points')->default(0);

        $table->foreign('account_id')->references('id')->on('accounts')->onDelete('cascade');
    });

然后是Entrust Migration(只有下面有问题的部分):

    Schema::create('__acc_role_user', function (Blueprint $table) {
        $table->integer('user_id')->unsigned();
        $table->integer('role_id')->unsigned();

        $table->foreign('user_id')->references('account_id')->on('__acc_accounts')
            ->onUpdate('cascade')->onDelete('cascade');
        $table->foreign('role_id')->references('id')->on('__acc_roles')
            ->onUpdate('cascade')->onDelete('cascade');

        $table->primary(['user_id', 'role_id']);
    });

1 个答案:

答案 0 :(得分:1)

这个sintax更好:

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('__acc_accounts', function($table)
    {
        $table->integer('account_id')->increments();
        $table->integer('points')->default(0);
    });

    Schema::table('__acc_accounts', function(Blueprint $table)
{
        $table->foreign('account_id')->references('id')->on('accounts')->onDelete('cascade');
    });
}


/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::drop('__acc_accounts');
}

非常重要!在您的迁移顺序中,必须:首先创建表'帐户'并且在' __ acc_accounts'。

之后
  

应在创建引用的表之后创建带有外键的表。

http://blog.kongnir.com/2015/03/08/laravel-order-of-migrations-with-foreign-keys/可以帮助您理解这一点。