Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
431 views
in Technique[技术] by (71.8m points)

php - 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 :)

question from:https://stackoverflow.com/questions/11996823/cakephp-check-if-record-exists

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...