【问题标题】:Laravel 5.2, cannot add foreign key constraintLaravel 5.2,无法添加外键约束
【发布时间】:2016-11-11 11:51:22
【问题描述】:

我真的需要帮助,我使用了 laravel 的“make:auth”功能,现在我试图用框架生成的“用户”表创建一个外键。但它总是抛出一个错误 - (一般错误:1215 无法添加外键约束)。它只有一个错误,即我试图在“用户”表中建立表关系。 我已经被困在这里一段时间了,这是我的代码,我需要你们的帮助。提前谢谢你!

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string('username');
            $table->integer('number');
            $table->string('email')->unique();
            $table->string('avatar')->default('default.jpg');
            $table->string('password');
            $table->string('role');

            $table->rememberToken();
            $table->timestamps();

        });

        Schema::create('post', function (Blueprint $table) {
            $table->increments('id');
            $table->string('photo')->default('default.jpg');
            $table->text('description');
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('user');
            $table->timestamps();
        });
    }

【问题讨论】:

    标签: foreign-keys laravel-5.2 database-migration foreign-key-relationship


    【解决方案1】:

    这应该是您在外键声明处的拼写错误。尝试将其更改为:

    $table->foreign('user_id')->references('id')->on('users');
    

    希望对你有帮助 =)

    【讨论】:

    • f***ccckkkk!!哈哈哈谢谢先生,我忘记了 Laravel 的命名约定。谢谢先生。
    • @MencioLicious 先生,欢迎您,我很高兴听到我能够提供帮助。您介意标记接受我的回答吗,谢谢=)
    猜你喜欢
    • 2017-03-03
    • 2016-06-27
    • 2020-09-12
    • 2019-10-26
    • 1970-01-01
    • 2021-10-27
    • 2018-11-25
    • 2017-09-06
    • 1970-01-01
    相关资源
    最近更新 更多