2011-04-12 70 views

回答

3

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

+0

它必须通过$ _has_many – sheeks06 2011-04-12 08:10:15

+0

你是什么意思?在我的示例模型has_many items中,所以$ model-> items是一个has_many相关的对象。 – biakaveron 2011-04-12 10:09:33

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

任何工作?像设置模型的默认排序? – sheeks06 2011-04-12 04:23:41

+0

@ sheeks06:不是内建的,但你可以很容易地扩展自己的。 – zerkms 2011-04-12 04:24:23

+0

这是完美的:)谢谢! – sheeks06 2011-04-12 04:33:36