如何避免“;重复键值违反唯一约束“;使用拉拉威尔的雄辩


How to avoid "duplicate key value violates unique constraint" using Laravel eloquent?

考虑以下代码,使用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()

我如何可能解决这个问题

只需将其封装在try-catch块中并捕获QueryException如果您只想摆脱它。