php - 无法添加外键约束 - Laravel Entrust

标签 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');
    });

然后委托(delegate)迁移(下面仅列出有问题的部分):

    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']);
    });

最佳答案

这个语法更好:

/**
 * 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');
}

非常重要!您的迁移顺序必须是:首先创建表“accounts”,然后创建表“__acc_accounts”。

Tables with foreign keys should be created after the tables they reference to have been created.

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

关于php - 无法添加外键约束 - Laravel Entrust,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37927178/

相关文章:

php - Kafka - 如何监视新消息

php - Laravel Eloquent 从多个相关表中获取数据

php - 提取位标志的最有效方法

php - 如何解决 Laravel 中检查数据库值/变量可用性的问题

php - 将记录从数据库添加到ajax数组

php - 如何在 PHP 中管理嵌套数据库事务?

php - PHP和MySQL-mysqli_free_result()期望参数1为mysqli_result,在第110行给出的 bool 值

mysql搜索替换涉及 "http://"时

laravel - Laravel 中具有自定义属性的自定义验证消息

php - 如何在 laravel 5.3 上将参数传递给模态?