It sounds like you want to make the ORM where call dependent on the relevant filter key being present. The following code should do what you're looking for, it works for me, does it do what you want?
It would be neater if it didn't allow for the key-name/field-name distinction (Role
vs. RoleId
).
application/classes/Model/Object
:
class Model_Object extends ORM {
// Map from filter key names to model field names
protected static $_filter_map = array(
'Role' => 'RoleId',
// ...
);
public static function get_objects($filters = array())
{
$objects = ORM::factory('object');
foreach($filters as $key => $value)
{
if ($field = Arr::get(self::$_filter_map, $key))
{
$operator = (is_array($value)) ? 'IN' : '=';
$objects->where($field, $operator, $value);
} else {
throw new Kohana_Exception(
'Unknown filter key :key',
array(':key' => $key)
);
}
}
return $objects->find_all();
}
}
Some examples, first all objects:
Model_Object::get_objects( array() );
All objects with RoleId equal to 2:
Model_Object::get_objects( array('Role' => 2) );
All objects with role_id in (2,3,5) AND user_id = 1:
Model_Object::get_objects( array(
'Role' => array(2,3,5),
'User' => 1
) );
Note that this last one requires you to have:
protected static $_filter_map = array(
'Role' => 'role_id',
'User' => 'user_id', // where `user_id` is a db field name
// ...
);
OR to change/simplify the get_objects
function to
$objects = ORM::factory('object');
foreach($filters as $key => $value)
{
$field = Arr::get(self::$_filter_map, $key, $key);
$operator = is_array($value) ? 'IN' : '=';
$objects->where($field, $operator, $value);
}
return $objects->find_all();