comebal
comebal

Reputation: 946

How to use the "LIKE" statement in mongodb cakephp

I am using ICHIKAWAY's mongodb driver for cakephp.

One thing that I don't really get is how to perform a "LIKE" statement in cakephp using MONGODB.

I tried this statement:

$users = $this->User->find('all', array('conditions' => array('data_type' => 'user', 'profile.firstname LIKE' => '%'.$string)));

but its not working since "LIKE" is an mysql function.

Thanks for the suggestions.

Upvotes: 2

Views: 1297

Answers (1)

AD7six
AD7six

Reputation: 66217

Use MongoRegex

Mongo DB has a LIKE operator - it's simply a regular expression, to use it:

$users = $this->User->find('all', array(
    'conditions' => array(
        'data_type' => 'user', 
        'profile.firstname' => new MongoRegex("/$string/i")
     )
));

There's an SQL Compatibilty behavior

The Mongodb driver contains a behavior providing sql syntax compatibility. To use it, simply make sure your model is using this behavior:

class User extends AppModel {

    $actsAs = array(
        'MongoDB.SqlCompatible'
    )
}

And then you can use your query exactly as it appears in the question:

$users = $this->User->find('all', array(
    'conditions' => array(
        'data_type' => 'user', 
        'profile.firstname LIKE' => '%'.$string
     )
));

Upvotes: 3

Related Questions