Cakephp check if record exists
Asked Answered
C

2

39

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

Concertante answered 16/8, 2012 at 23:25 Comment(0)
H
69

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
}
Hovercraft answered 16/8, 2012 at 23:36 Comment(3)
Thank you very much, didn't notice this function was around :)Concertante
Unknown method "hasAny"Diathesis
@Diathesis in Cake 4.x it's actually called exists(). You can throw params in there nowadays.Concertante
P
1

For CakePHP 3, you can use the exists() method, with similar input values.

exists(arrayArrayAccess $conditions): bool
Returns true if there is any record in this repository matching the specified conditions.

https://api.cakephp.org/3.1/class-Cake.ORM.Table.html#exists()

Petrochemistry answered 11/1 at 12:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.