Laravel Eloquent,如何处理 UNIQUE 错误?

我有一个 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)is时捕获异常true。


有没有更好的解决办法?


编辑


我注意到在Illuminate\Database\Eloquent\BuilderLaravel 中无论如何都会进行双重查询,这有点令人伤心:


public function findOrNew($id, $columns = ['*'])

{

    if (! is_null($model = $this->find($id, $columns))) {

        return $model;

    }


    return $this->newModelInstance();

}


慕少森
浏览 179回答 3
3回答
打开App,查看更多内容
随时随地看视频慕课网APP