0

例如我的Modelhas 方法get_objects,我通过以下来源搜索它们:

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;
}

因此,该代码仅在过滤器存在时才起作用,当过滤器中没有值时,我将没有任何记录而不是全部(我想要所有记录),如何使它更好?

4

1 回答 1

1

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();
于 2013-02-12T00:12:19.533 回答