聽起來好像你想讓ORM的調用依賴於相關的過濾器關鍵字。下面的代碼應該做你正在尋找的東西,它適用於我,它做你想做的?
如果它不允許鍵名/字段名稱區分(Role
與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();
}
}
一些例子,第一所有對象:
Model_Object::get_objects(array());
與角色ID的所有對象等於2:
Model_Object::get_objects(array('Role' => 2));
在ROLE_ID(2的所有對象, 3,5)AND user_id = 1:
Model_Object::get_objects(array(
'Role' => array(2,3,5),
'User' => 1
));
注意,這最後一個需要你有:
protected static $_filter_map = array(
'Role' => 'role_id',
'User' => 'user_id', // where `user_id` is a db field name
// ...
);
或更改/簡化get_objects
功能
$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();