now*_*wox 3 php laravel eloquent
我有一个 MySQL 约束来确保复合键的唯一性。在我的模型中插入新记录时,Foo出现预期错误:
$foo = new Foo(['foo' => 42, 'bar => 1]);
$foo->save();
Run Code Online (Sandbox Code Playgroud)
错误:
SQLSTATE[23000]:违反完整性约束:1062 键 'Unique' 的重复条目 '42'...
避免此错误的一种解决方案是在插入之前查询模型:
if (!Foo::where('foo', 42)->where('bar', 1)->first()) {
$foo = new Foo(['foo' => 42, 'bar => 1]);
$foo->save();
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是在preg_match(/UNIQUE/, $e->message)is时捕获异常true。
有没有更好的解决办法?
编辑
我注意到在Illuminate\Database\Eloquent\BuilderLaravel 中无论如何都会进行双重查询,这有点令人伤心:
public function findOrNew($id, $columns = ['*'])
{
if (! is_null($model = $this->find($id, $columns))) {
return $model;
}
return $this->newModelInstance();
}
Run Code Online (Sandbox Code Playgroud)
在一般情况下,您应该使用错误代码而不是任何正则表达式来处理数据库错误。
在您的特定情况下,如果您的意图是覆盖/更新现有数据,则预查询或使用自动为您执行此操作的 Laravel 方法可能更可取。
如果您想一般地预测错误并处理它,您应该执行以下操作:
try {
$foo = new Foo(['foo' => 42, 'bar' => 1]);
$foo->save();
} catch (\Exception $e) { // It's actually a QueryException but this works too
if ($e->getCode() == 23000) {
// Deal with duplicate key error
}
}
Run Code Online (Sandbox Code Playgroud)
有关错误代码的详尽列表,请参阅https://dev.mysql.com/doc/refman/5.5/en/error-reference.html(但理想情况下,您只需要处理几个特定的错误和非常具体的情况。
最后,SQLON DUPLICATE KEY UPDATE也可能对您有用,但是如果您这样做是为了默默地忽略新值,那么我建议您改为进行错误处理。
| 归档时间: |
|
| 查看次数: |
5629 次 |
| 最近记录: |