【问题标题】:Laravel - Foreign key constraint is incorrectly formed - missing nullableLaravel - 外键约束的格式不正确 - 缺少可为空的
【发布时间】:2022-06-15 22:37:59
【问题描述】:

我想创建一个表,其中有两个条目引用我的“用户”表中的不同用户。我使用 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();
    });
}

【问题讨论】:

    标签: php sql laravel eloquent


    【解决方案1】:

    原因很简单,我对 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();
        });
    }
    

    【讨论】:

      猜你喜欢
      • 2017-10-04
      • 2017-10-03
      • 2019-07-25
      • 2018-02-19
      • 2021-05-26
      • 2020-09-24
      • 2019-11-02
      • 2023-03-19
      • 2020-04-15
      相关资源
      最近更新 更多