Question

I using Phalcon PHP as PHP MVC Framework with MongoDB. I can find object according with some criteria:

$user = User::findFirst(array(array('username' => $login, 'email'=> $login)));

As you can note, this request will return me the record according logical AND operator between conditions. I need to form request that will return result according with OR operator between conditions.

The problem also is that I'm using MongoDB, so, as I can suppose, I can't write PHQL request manually.

Was it helpful?

Solution

Just a matter of mangling PHP arrays

$user = User::findFirst( array( 
    '$or' => array(
        array( 'username' => $login),
        array( 'email' => $login)
    )
 ));

So not only do I show the answer but also how my totals non PHP mind solves this problem:

$result = '{ "$or": [ { "username": "login" }, { "email": "login" } ] }';
echo var_dump( json_decode( $result ) );

$test = array( 
    '$or' => array(
         array( 'username' => 'login'), array( 'email' => 'login')
     )
);

echo json_encode( $test ) ."\n"

So in just a few lines we converted and proved. So since you knew the JSON from either the manual page or reading another question on SO, just convert it. And it's one of the reasons I submit the valid JSON in responses here, is so that the logic can be translated into just about any language implementation.

OTHER TIPS

You can pass column names as string in first param:

$user = User::findFirst('username = "'.$login.'" OR email = "'.$login.'"');
$result = '{ "$or": [ { "username": "login" }, { "email": "login" } ] }';
User::findFirst(array(json_decode($query,true)));

$result is the exact json which can be used to trigger queries in mongodb command line

json_decode with 2nd parameter true will output the array style format of JSON

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top