0

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

4

2 回答 2

3

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

于 2011-04-12T07:36:32.090 回答
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;
    }
}
于 2011-04-12T04:20:57.380 回答