【发布时间】:2011-04-12 04:12:55
【问题描述】:
如何在 Kohana 3 中订购使用 has_many 关联的查询?
【问题讨论】:
标签: php mysql kohana kohana-3 kohana-orm
如何在 Kohana 3 中订购使用 has_many 关联的查询?
【问题讨论】:
标签: php mysql kohana kohana-3 kohana-orm
您是否尝试过类似$model->items->order_by('fieldname')->find_all() 的方法? __get() 方法返回 Query_Builder 对象,而不是 Database_Result,因此您可以根据需要添加 QBuilder 的条件(where/order_by/etc)。
【讨论】:
根据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;
}
}
【讨论】: