【问题标题】:CakePHP ignore Record not found in table exceptionCakePHP 忽略在表异常中找不到记录
【发布时间】:2025-12-07 08:55:02
【问题描述】:

没有 ID 为 0 的记录。我正在做

$id = 0;
try { 
  $object = $this->MyModel->get($id); 
} catch(Exception $e){
  //Nothing
}

而且我仍然抛出异常“表中未找到记录”。

我如何忽略给定 ID 的 get($id) 没有记录并避免异常?

【问题讨论】:

  • 这能回答你的问题吗? Catch Exception in Cakephp 3 : not working
  • 另外,这里的具体例外是\Cake\Datasource\Exception\RecordNotFoundException
  • @ndm 我也试图捕捉那个确切的异常,但它没有用。
  • 你读过@Szymon 的链接吗?正是这个问题。

标签: php exception cakephp cakephp-3.0


【解决方案1】:

$this->MyModel->find('all', ['conditions' => ['id' => $id]])->first(); 似乎是最短的代码,不会出现不存在元素的错误。

另一个问题是,我使用了Exception 而不是正确的\Exception,这就是为什么尽管使用了try-catch-block 还是抛出了错误。

【讨论】:

    【解决方案2】:

    您也可以尝试将关系设为LEFT 加入。

    Insde MyModelTable.php
    
            $this->MyModel->belongsTo('ParentTable', [
                'foreignKey' => 'parent_id',
                'joinType' => 'LEFT',
            ]);
    

    【讨论】:

      【解决方案3】:

      为什么不使用 if 语句?

      $id = 0;
      $object = [];
      if ($id){
        $object = $this->MyModel->get($id); 
      } else{
        $object = [];
      }
      

      【讨论】:

      • 不,这并不能保证另一个 id=1231243233 不存在。我根本不想出错。