'CakePHP ignore Record not found in table exception
There is no record with ID 0 on purpos. And I'm doing
$id = 0;
try {
$object = $this->MyModel->get($id);
} catch(Exception $e){
//Nothing
}
And I still get the exception thrown "Record not found in table".
How can I ignore, that there is no record with the given ID with get($id) and avoid the exception?
Solution 1:[1]
$this->MyModel->find('all', ['conditions' => ['id' => $id]])->first(); seems to be the shortest code without getting an error on non-existence of an element.
The other problem was, that I used Exception instead of the correct \Exception, that's why the error was thrown despite the try-catch-block.
Solution 2:[2]
You can also try making the relationship a LEFT join.
Insde MyModelTable.php
$this->MyModel->belongsTo('ParentTable', [
'foreignKey' => 'parent_id',
'joinType' => 'LEFT',
]);
Solution 3:[3]
Why not using if statement?
$id = 0;
$object = [];
if ($id){
$object = $this->MyModel->get($id);
} else{
$object = [];
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Martin Cup |
| Solution 2 | Paul Trimor |
| Solution 3 | Touch sophonara |
