I'm a new dev in CakePHP and I'm consfusing about this case :
Now I have a table users with model User, I want check the exist of record with id = 4 : If the record exists, return it, if not return message error, there are 2 methods that I think :
Solution 1 :
$this->Model->id = 4;
if ($this->Model->exists()) {
return $this->Model->read();
} else {
return "ERROR";
}
Solution 2 :
$data = $this->Model->find('first', array(
'conditions' => array('Model.id' => 4)
));
if (!empty($data)) {
return $data;
} else {
return "ERROR";
}
I don't know what is better or more optimized (I think in Solution 1 Cake will do 2 queries, is it ?), please give me answer for the best solution.Sorry for my bad English.
There is no need for two queries.
class FooModel extends Model {
public function view($id) {
$result = $this->find('first', [
'conditions' => [
$this->alias . '.' . $this->primaryKey => $id
]
]);
if (empty($result)) {
throw new \NotFoundException('Foo record not found');
}
}
return $result;
}
Then just call the method in your controller action:
public function view($id) {
$this->set('foo', $this->FooModel->view($id));
}
Or catch the exception if you want to do something else than displaying the not found error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With