繁体   English   中英

Laravel - 外键约束的格式不正确 - 缺少可为空的

[英]Laravel - Foreign key constraint is incorrectly formed - missing nullable

我想创建一个表,其中有两个条目引用我的“用户”表中的不同用户。 我使用 user_id 和 from_id。

运行迁移时,出现错误“外键约束格式不正确”。 当我删除两个 from_id 行时,它可以工作。 这是我的迁移:

public function up()
{
    Schema::create('applicationpicture', function (Blueprint $table) {
        $table->id();

        $table->char('url')->default('');

        // When I remove the following two lines, everything works.
        $table->foreignId('from_id');
        $table->foreign('from_id')->references('id')->on('users')->onDelete('set null');

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

        $table->foreignId('event_id')->nullable();
        $table->foreign('event_id')->references('id')->on('events')->onDelete('set null');

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

这样做,Laravel 7.x 有更简单和干净的方法来做同样的事情:

public function up()
{
    Schema::create('applicationpicture', function (Blueprint $table) {
        $table->id();

        $table->char('url')->default('');


        $table->foreignId('from_id')->nullable()->constrained('users');

        $table->foreignId('user_id')->nullable()->constrained()->cascadeOnDelete();

        $table->foreignId('event_id')->nullable()->constrained();

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

迁移失败的原因是您的外键设置为 null onDelete 但不能同时为空。

public function up()
{
    Schema::create('applicationpicture', function (Blueprint $table) {
        $table->id();

        $table->char('url')->default('');

        // Problem lies here just add nullable()
        $table->foreignId('from_id')->nullable();
        $table->foreign('from_id')->references('id')->on('users')->onDelete('set null');

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

        $table->foreignId('event_id')->nullable();
        $table->foreign('event_id')->references('id')->on('events')->onDelete('set null');

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

原因很简单,我对 from_id 字段使用了 onDelete('set null'),但我忘记添加 nullable() 定义。 所以正确的迁移看起来像这样:

public function up()
{
    Schema::create('applicationpicture', function (Blueprint $table) {
        $table->id();

        $table->char('url')->default('');

        $table->foreignId('from_id')->nullable();  // Added nullable()
        $table->foreign('from_id')->references('id')->on('users')->onDelete('set null');

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

        $table->foreignId('event_id')->nullable();
        $table->foreign('event_id')->references('id')->on('events')->onDelete('set null');

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM