【问题标题】:SQLSTATE[23000]: Integrity constraint violation: 19 FOREIGN KEY constraint failed => LaravelSQLSTATE [23000]:完整性约束违规:19 FOREIGN KEY 约束失败 => Laravel
【发布时间】:2021-01-26 10:24:18
【问题描述】:

您好,我正在尝试添加两个引用同一个表的外键列。但我被这个错误困住了。我花了很多时间试图找出我的代码的问题。我已经在stackoverflow中浏览了所有可能的重复帖子,但我找不到解决方案。

我的代码很长,所以我在这里提到了重要的部分,如果您需要有关此问题的任何进一步信息,请告诉我。

这是我的外键关系

            $table->unsignedBigInteger('country_id');
            $table->unsignedBigInteger('city_id');
            $table->unsignedBigInteger('work_location');
            $table->unsignedBigInteger('citizenship');
            $table->foreign('country_id')->references('id')->on('countries');
            $table->foreign('city_id')->references('id')->on('cities');
            $table->foreign('work_location')->references('id')->on('cities');
            $table->foreign('citizenship')->references('id')->on('countries');

这些是我的主要模特关系

 public function city()
    {
        return $this->belongsTo(City::class, 'city_id');
    }

    public function country()
    {
        return $this->belongsTo(Country::class,'country_id');
    }

    public function citizenship()
    {
        return $this->belongsTo(Country::class,'citizenship');
    }

    public function work_location()
    {
        return $this->belongsTo(City::class, 'work_location');
    }

这就是我通过 phpunit 向模型发送数据的方式

            'citizenship'=>Country::factory()->create();,
            'work_location'=>City::factory()->create();,
            'city_id' => City::factory()->create();,
            'country_id' => Country::factory()->create(),

【问题讨论】:

    标签: php sqlite eloquent laravel-8


    【解决方案1】:

    迁移是根据创建日期加载的,可能是因为您在数据库中创建关系之前定义了一些关系。

    换句话说,城市、国家、公民身份和工作地点迁移必须在被引用之前创建。

    您能否附上项目迁移的屏幕截图?只是为了了解更多细节。

    【讨论】:

      猜你喜欢
      • 2020-12-28
      • 2020-01-28
      • 2018-03-20
      • 2021-06-10
      • 2021-03-24
      • 1970-01-01
      • 2020-09-17
      • 2022-11-02
      • 2020-01-31
      相关资源
      最近更新 更多