Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Model::find / Model::findFirst conditions from associative array

Elo bird lovers!

Is there any way to pass in an associative array as conditions for find / findFirst? I've found no clue in the forums/docs/source...

You can already bind parameters like so:

$conditions = ['type_id'=>42, 'enabled'=>1];
$robot = Robot::findFirst([
    'conditions' => 'type_id=:type_id: AND enabled=:enabled:',
    'bind' => $conditions,
]);

I was wondering if you could do something like (laziness rulz):

$conditions = ['type_id'=>42, 'enabled'=>1];
$robot = Robot::findFirst([
    'conditions' => $conditions,
]);

So if the conditions is an array, it expands automagically to the correct string and bind?

I could also write a static method, but would rather use the built-in features if there is such :]

class MyModel extends Phalcon\Mvc\Model {
    public static function arrayConditions(array $conditions, array $parameteres=[]) {
        if(count($conditions)>0) {
            $c = '';
            foreach($conditions as $field=>$value) $c.= ' AND '.$field.'=:'.$field.':';
            $c = substr($c,5);
            $parameters = array_merge($parameters, [
                'conditions' => $c,
                'bind' => $conditions,
            ]);
        }
        return $parameters;
    }
}

$conditions = ['type_id'=>42, 'enabled'=>1];
$robot = Robot::findFirst(MyModel::arrayConditions($conditions));

Cheers!



33.6k
Accepted
answer
edited Jul '15

That way is not supported as it's too limited, conditions in SQL can have AND, OR, associations with parentheses, etc. And it only seems to work with a first level AND.

True, but could still come handy lots of times :] I'll use a helper method then, thank you!

That way is not supported as it's very limited, conditions in SQL can have AND, OR, associations with parentheses, etc. And it only seems to work with a first level AND.