微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Laravel迁移:创建2个表Users表和Advertisements表外键引用用户ID

如何解决Laravel迁移:创建2个表Users表和Advertisements表外键引用用户ID

我正在尝试创建广告表,其中包含引用了用户表中“ id”列的“ user_id”列,但是没有运气。

错误消息开始,我注意到框架没有传递users表的'id'列。知道我要使用“ PHPMyAdmin”手动解决此问题。

我想知道是否还有其他方法可以解决此问题?

Users Schema:
       Schema::create('users',function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });

Advertisements Schema:
        Schema::create('advertisements',function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('user_id');
        $table->string('name');
        $table->text('description');
        $table->mediumtext('image')->nullabe;
        $table->timestamps();

        $table->foreign('user_id')
                ->reference('id')
                ->on('users')
                ->onDelete('cascade');
    });

错误

PDOException::("sqlSTATE[42000]: Syntax error or access violation: 1064 You have an error in your sql Syntax; check the manual that corresponds to your MariaDB server version for the right Syntax to use near ') on delete cascade' at line 1").
PDO::prepare("alter table `advertisements` add constraint `advertisements_user_id_foreign` foreign key (`user_id`) references `users` () on delete cascade")

解决方法

问题出在您的Advertisements迁移代码中,应将其放在-> references('id')而不是-> reference('id') >

Advertisements Schema:
        Schema::create('advertisements',function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('user_id');
        $table->string('name');
        $table->text('description');
        $table->mediumtext('image')->nullabe;
        $table->timestamps();

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。