Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cakephp check if record exists

Tags:

php

cakephp

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

like image 936
Jelmer Avatar asked Aug 16 '12 23:08

Jelmer


1 Answers

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 } 
like image 155
tigrang Avatar answered Sep 28 '22 16:09

tigrang