我有一個 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();}
- 3 回答
- 0 關注
- 197 瀏覽
添加回答
舉報
0/150
提交
取消