如何使用Laravel eloquent避免“重复键值违反唯一约束”?

时间:2016-07-26 17:51:26

标签: php postgresql laravel-5.2

考虑以下代码,使用Postgres + Laravel 5.2:

$post = Post::firstOrNew(['title'=> 'title test']);
$post->body = 'test body';
$post->save();

每当多个进程对我获得的相同数据进行处理时 Unique violation: 7 ERROR: duplicate key value violates unique constraint..

我尝试使用此处建议的交易 https://laracasts.com/discuss/channels/general-discussion/how-properly-use-the-lockforupdate-method 但后来我得到了Call to undefined method Illuminate\Database\Query\Builder::save()

例如:Post::firstOrNew([...])->lockForUpdate()

我怎样才能解决这个问题

1 个答案:

答案 0 :(得分:1)

将它包装在try catch块中并捕获QueryException如果你只是想搞清楚它。