Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method to check record exist in database, and then if true return record in CakePHP?

Tags:

php

mysql

cakephp

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.

like image 205
user3209287 Avatar asked Nov 10 '22 13:11

user3209287


1 Answers

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.

like image 113
floriank Avatar answered Nov 14 '22 22:11

floriank