简体   繁体   中英

Cakephp check if record exists

I am wondering, is there a function that allows me to check instantly if a record in the database exists?

Right now I am using the following piece of code to detect if a record exists, but I can imagine there is a simpler/better way.

$conditions = array(
    'conditions' => array(
         'User.id' => $this->Session->read('User.id'),
         'User.activation_key' => $this->Session->read('User.key')
     )
);
$result = $this->User->find('first', $conditions);
if (isset($result['User'])){
    //do something
}

Is there something like:

$conditions = array(
    'conditions' => array(
         'User.id' => $this->Session->read('User.id'),
         'User.security_key' => $this->Session->read('User.key')
    )
);
if ($this->User->exists($conditions)){
    //do something
}

Okay, yes there is. It's called exists() , but I need the same, but with parameters, so I can add my own conditions to the check.

I have searched google, but I can't find any topic about this. Well, a lot about php and mysql, but not about cakephp. I need a cake specific answer.

Thanks for your time :)

What you are looking for is Model::hasAny

Usage:

$conditions = array(
    'User.id' => $this->Session->read('User.id'),
    'User.security_key' => $this->Session->read('User.key')
);
if ($this->User->hasAny($conditions)){
    //do something
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM