Kohana 3:has_many和order_by

时间:2011-04-12 04:12:56

标签: php mysql kohana kohana-3 kohana-orm

如何在Kohana 3中订购使用has_many关联的查询?

2 个答案:

答案 0 :(得分:3)

您是否尝试过类似$model->items->order_by('fieldname')->find_all()的内容? __get()方法返回Query_Builder对象,而不是Database_Result,因此您可以根据需要添加QBuilder的条件(其中/ order_by / etc)。

答案 1 :(得分:1)

根据Kohana_ORM::__get()实施 - 您不能。

所有这一切只是组成where条件而没有任何添加排序的可能性:

    elseif (isset($this->_has_many[$column]))
    {
        $model = ORM::factory($this->_has_many[$column]['model']);

        if (isset($this->_has_many[$column]['through']))
        {
            // Grab has_many "through" relationship table
            $through = $this->_has_many[$column]['through'];

            // Join on through model's target foreign key (far_key) and target model's primary key
            $join_col1 = $through.'.'.$this->_has_many[$column]['far_key'];
            $join_col2 = $model->_table_name.'.'.$model->_primary_key;

            $model->join($through)->on($join_col1, '=', $join_col2);

            // Through table's source foreign key (foreign_key) should be this model's primary key
            $col = $through.'.'.$this->_has_many[$column]['foreign_key'];
            $val = $this->pk();
        }
        else
        {
            // Simple has_many relationship, search where target model's foreign key is this model's primary key
            $col = $model->_table_name.'.'.$this->_has_many[$column]['foreign_key'];
            $val = $this->pk();
        }

        return $model->where($col, '=', $val);
    }

但是你可以编写自己的课程ORM并在那里重新实现__get。您需要重写我上面给出的部分(如果isset($this->_has_many[$column]))或者将控件传递给parent::__get($column)。在这种情况下,您可以向_has_many安装数组添加一个参数,例如order_by,并使用相关模型进行排序。

在伪代码中:

class ORM extends Kohana_ORM
{
    public function __get($column)
    {
        $result = parent::__get($column);

        if (isset($this->_has_many[$column]) && !empty($this->_has_many[$column]['order_by'])) {
            $result->order_by($this->_has_many[$column]['order_by']);
        }

        return $result;
    }
}
相关问题