【问题标题】:Get Laravel Model->save() error code or message获取 Laravel Model->save() 错误代码或消息
【发布时间】:2019-12-31 04:48:24
【问题描述】:

laravel Model->save() 不会抛出数据库异常,我想检查列的唯一约束(没有主键或其他外键)。

当Model->save()返回false时,有什么方法可以得到消息的数据库错误代码?

【问题讨论】:

    标签: php mysql laravel error-handling eloquent


    【解决方案1】:

    你可以试试QueryException。捕获任何SQL 语法或查询错误。

    use Illuminate\Database\QueryException

    try {
    
            $model = Model::find($id);
            $model->name = 'joe';
            $model->save();
    
        } catch (QueryException $e) {
    
            dd($e->getMessage());
    
        }
    

    【讨论】:

    • 它用于创建但需要在行更新时出错。你怎么看?
    • 我更新了我的答案。但是代码是一样的。在try 中放入你的代码来更新或创建你的模型,
    • save 方法不会抛出任何数据库异常。 laravel.com/api/5.8/Illuminate/Database/Eloquent/…
    • 你应该使用Model::find($id)->update(['name' => 'test']); :)
    【解决方案2】:

    您可以在数据库中使用“UNIQUE”列,然后通过 QueryException 处理错误。

    【讨论】:

      【解决方案3】:

      => If you have label exists, See below error:
        "Exception message:SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'TEST  GO' for key 'materials_label_unique' (SQL: insert into `materials` (`label`, `updated_at`, `created_at`) values (TEST GO, 2019-08-27 09:53:47, 2019-08-27 09:53:47)) with code: 23000"
      
      function insertMaterial()
      {
          try {
              $material = new Materials;
              $material->label = "TEST GO";
              if( $material->save() ) {
                  return "True as a string";
              } else {
                  return "False as a string";
              }
          } catch (\Exception $e) {
              return 'Exception message:' . $e->getMessage() . ' with code: ' . $e->getCode();
          }
      }
      
      
      => If you'll try to find the non-existing record, See below error:
         "Exception message: Creating default object from the empty value with code: 0"
      
      function insertMaterial()
      {
          try {
              $material = Materials::find(1111);
              $material->label = "TEST GO";
              if( $material->save() ) {
                  return "True as a String";
              } else {
                  return "False as a String";
              }
          } catch (\Exception $e) {
              return 'Exception message:' . $e->getMessage() . ' with code: ' . $e->getCode();
          }
      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-07-31
        • 1970-01-01
        • 1970-01-01
        • 2015-06-27
        • 2018-04-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多