2013-02-11 53 views
0

比如我Model有方法get_objects,我對下面的源搜索他們:如何在ORM中製作過濾器?

class Model_Object extends ORM { 

public function get_objects($filters = array()) 
{ 

     if (!empty($filters['Role'])) 
      $role = $filters['Role']; 
      else 
     $role = NULL; 


     $objects = ORM::factory('object') 
         ->where('RoleId','=',$role) 
         ->find_all(); 

     return $objects; 
} 

因此,當過濾器存在的代碼只會工作,當過濾器沒有價值,我會沒有任何記錄,而不是(我想要所有的記錄),如何讓它變得更好?

回答

1

聽起來好像你想讓ORM的調用依賴於相關的過濾器關鍵字。下面的代碼應該做你正在尋找的東西,它適用於我,它做你想做的?

如果它不允許鍵名/字段名稱區分(RoleRoleId),它會更整齊一些。

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();