We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

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!



34.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.



895

True, but could still come handy lots of times :]

Agree totally, and wondering whether Phalcon ever gained this ability. While there's the rare time when you want different logic, almost always you want to fetch with simple AND based restrictions. The ethos should be to support the most common case with the simplest possible mechanism, and just ensure there's a way to cover other cases when required.