【发布时间】:2019-11-03 08:16:40
【问题描述】:
我有一个 MySQL 约束来确保复合键的唯一性。在我的模型Foo 中插入新记录时,我得到了预期的错误:
$foo = new Foo(['foo' => 42, 'bar => 1]);
$foo->save();
错误:
SQLSTATE[23000]:违反完整性约束:1062 键 'Unique' 的重复条目 '42'...
避免此错误的一种解决方案是在插入之前查询模型:
if (!Foo::where('foo', 42)->where('bar', 1)->first()) {
$foo = new Foo(['foo' => 42, 'bar => 1]);
$foo->save();
}
另一种方法是在preg_match(/UNIQUE/, $e->message) 为true 时捕获异常。
有没有更好的解决方案?
编辑
我注意到在Illuminate\Database\Eloquent\Builder Laravel 中无论如何都会执行双重查询,这有点令人难过:
public function findOrNew($id, $columns = ['*'])
{
if (! is_null($model = $this->find($id, $columns))) {
return $model;
}
return $this->newModelInstance();
}
【问题讨论】:
-
为什么不更新您的迁移文件以消除约束?