doudun2565 2019-06-20 13:33
浏览 295
已采纳

Laravel Eloquent,如何处理UNIQUE错误?

I have a MySQL constraint to ensure unique on a composite key. When inserting a new record in my model Foo I get the expected error:

$foo = new Foo(['foo' => 42, 'bar => 1]);
$foo->save();

Error:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '42' for key 'Unique'...

One solution to avoid this error is to query the model before inserting:

if (!Foo::where('foo', 42)->where('bar', 1)->first()) {
  $foo = new Foo(['foo' => 42, 'bar => 1]);
  $foo->save();
}

Another one would be to catch the exception when preg_match(/UNIQUE/, $e->message) is true.

Is there any better solution?

EDIT

I noticed that in Illuminate\Database\Eloquent\Builder Laravel does the double query anyway which is a bit sad:

public function findOrNew($id, $columns = ['*'])
{
    if (! is_null($model = $this->find($id, $columns))) {
        return $model;
    }

    return $this->newModelInstance();
}
  • 写回答

4条回答 默认 最新

  • douchan7552 2019-06-20 13:56
    关注

    In the general case you should be dealing with database errors using the error code and not any regex.

    In your particular case pre-querying or using a Laravel method that does that automatically for you, might be preferable if your intention is to overwrite/update existing data.

    If you want to generally anticipate an error and handle it you should do something like:

    try {
       $foo = new Foo(['foo' => 42, 'bar' => 1]);
       $foo->save();
    } catch (\Exception $e) { // It's actually a QueryException but this works too
       if ($e->getCode() == 23000) {
           // Deal with duplicate key error  
       }
    }
    

    Refer to https://dev.mysql.com/doc/refman/5.5/en/error-reference.html for an exhaustive list of error codes (but ideally you'd only need to deal with a couple of specific errors and under very specific circumstances.

    Lastly the SQL ON DUPLICATE KEY UPDATE might also work for you, however if you are doing this to silently ignore the new values then I suggest you do the error handling instead.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀