Kohana 3 で has_many アソシエーションを使用するクエリを注文するにはどうすればよいですか?
1288 次
2 に答える
3
次のようなことを試しました$model->items->order_by('fieldname')->find_all()
か?__get()
メソッドは Database_Result ではなく Query_Builder オブジェクトを返すため、必要に応じて 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
。上記の部分 ( if isset($this->_has_many[$column])
) を少し書き直すか、コントロールを other に渡す必要がありparent::__get($column)
ます。この場合、_has_many
配列をセットアップするためにもう 1 つのパラメーターを自由に追加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 に答える