【问题标题】:How to avoid "duplicate key value violates unique constraint" using Laravel eloquent?如何使用 Laravel eloquent 避免“重复键值违反唯一约束”?
【发布时间】:2016-07-27 03:07:41
【问题描述】:

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

我怎么可能解决这个问题

【问题讨论】:

  • firstOrNew() 不接受两个参数吗?如果是exists 还是new,您提供什么查询?
  • 我在生成假模型时遇到了这个问题,每个模型自己都生成了一个假的相关模型。解决方案是生成一次相关模型,并在创建过程中将其分配给每个模型。

标签: php postgresql laravel-5.2


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-13
    • 2020-03-27
    • 2013-06-23
    • 2016-06-12
    • 2013-03-15
    • 2016-11-27
    • 2018-03-14
    • 2016-09-27
    相关资源
    最近更新 更多