【问题标题】:laravel save() chokes with "Integrity constraint violation" - all keys are set properlylaravel save() 因“违反完整性约束”而窒息 - 所有键都已正确设置
【发布时间】:2014-12-27 06:06:31
【问题描述】:

迁移:

Schema::create('burbs', function($table)
    {
        $table->engine = 'InnoDB';

        $table->increments('id');
        $table->integer('parent_location_id')->nullable()->index()->unsigned();
        $table->integer('location_id')->nullable()->index()->unsigned();
        $table->timestamps();

        $table->foreign('parent_location_id')->references('id')->on('locations')->onDelete('cascade');
        $table->foreign('location_id')->references('id')->on('locations')->onDelete('cascade');

    });

模型(Burb)

    protected $fillable = ['parent_location_id','location_id'];

当我这样做时:

$burb = Burb::where(['location_id' => $location_id])->first();
    if(!$burb) $burb = new Burb;
    $burb->parent_location_id = $parent_id;
    $burb->location_id = $location_id;
    $burb->save();

得到这个:

违反完整性约束:1452 无法添加或更新子项 行:外键约束失败(tb_prod.burbs, CONSTRAINT burbs_location_id_foreign 外键 (location_id) 参考 locations (id) 删除级联)

SQL 插入到burbs (parent_location_id, location_id, updated_at, created_at) 值 (12776, 321036, 2014-10-30 20:38:24, 2014-10-30 20:38:24)

第一个和第二个 ID 都存在于位置表中。

是的,parent_location_id 和 location_id 都是同一个位置表的键。

我也试过:FirstOrNew([]);和 FirstOrCreate([]);我什至尝试过

$burb->parent_location()->save($locationObj);

最后一个代码产生了“未知方法 save(),而在我的 Burb 模型中:

public function parent_location()
{
    return $this->belongsTo('Location','parent_location_id');
}

.....我很茫然,我对laravel并不陌生,但我只花了3个小时调试这个。少了什么东西?快把我逼疯了!

【问题讨论】:

  • 如果你这样做会发生什么$burb->parent_location->save($locationObj);
  • 您确定这些 ID 存在于 locations 表中吗?
  • 也许您正在使用另一个数据库,请确保 tb_prod 数据库包含有效的密钥
  • 乔纳森,我收到“未知方法保存()”错误。 Scopey,是的,我手动运行“SELECT WHERE”和 Razor,只有一个 DB。

标签: php laravel eloquent


【解决方案1】:

您的迁移中的->index()and->nullable() 真的有必要吗?它们是外键,所以......但它取决于你:D

尝试将您的迁移更改为:

Schema::create('burbs', function($table)
    {
        $table->engine = 'InnoDB';

        $table->increments('id');
        $table->integer('parent_location_id')->unsigned();
        $table->integer('location_id')->unsigned();
        $table->timestamps();

        $table->foreign('parent_location_id')->references('id')->on('locations')->onDelete('cascade');
        $table->foreign('location_id')->references('id')->on('locations')->onDelete('cascade');

    });

因为上次我遇到了同样的问题,但在我的情况下,我忘了放

->无符号()

【讨论】:

    【解决方案2】:

    我觉得自己非常愚蠢。第二个 id (location_id) 是 Insert 上错误表中的错误 id。当我手动(在 mysql 中)运行几个测试用例时,我很幸运这些 Id 存在,但对于大多数实时数据来说它都失败了。

    感谢您的所有帮助。在一些相关的说明上:忘记 ->unsigned() 以前给我带来了如此多的悲伤。

    【讨论】:

      猜你喜欢
      • 2019-04-12
      • 1970-01-01
      • 2016-08-11
      • 1970-01-01
      • 2019-01-02
      • 2017-09-11
      • 2020-06-14
      • 2016-05-25
      相关资源
      最近更新 更多