【问题标题】:Laravel Migration: Creating 2 tables Users Table & Advertisements Table (with foreign key referring to user's id)Laravel 迁移:创建 2 个表用户表和广告表(外键引用用户 ID)
【发布时间】:2021-02-20 05:13:10
【问题描述】:

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

在错误消息中,我注意到框架没有传递用户表的列“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")

【问题讨论】:

    标签: laravel mariadb laravel-6 laravel-8 laravel-migrations


    【解决方案1】:

    问题出在您的广告迁移代码中,您应该把它放在 ->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');
        });
    

    【讨论】:

    • 我很尴尬因为这个错字:)。非常感谢您的帮助。
    • 很高兴。
    猜你喜欢
    • 2019-11-05
    • 2018-05-16
    • 2017-06-05
    • 1970-01-01
    • 2016-03-25
    • 1970-01-01
    • 2015-05-05
    • 2023-03-31
    • 2021-02-18
    相关资源
    最近更新 更多