Laravel 迁移:创建 2 个表用户 Table 和广告 Table(外键引用用户 ID)

Laravel Migration: Creating 2 tables Users Table & Advertisements Table (with foreign key referring to user's id)

我正在尝试创建广告 table,其中包含 'user_id' 列引用用户 table 中的 'id' 列,但没有成功。

根据错误消息,我注意到框架没有传递用户 table 的列 '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")

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