【发布时间】:2010-06-27 17:55:02
【问题描述】:
当我搜索一个“有很多”其他东西的模型时。
例如,一篇博客文章有很多类别。
在搜索具有关联类别的博客文章时,如何对关联的类别进行排序?返回数组时,它会忽略类别模型上的顺序并默认为其通常的 id 顺序。
干杯。
【问题讨论】:
标签: php cakephp model associations
当我搜索一个“有很多”其他东西的模型时。
例如,一篇博客文章有很多类别。
在搜索具有关联类别的博客文章时,如何对关联的类别进行排序?返回数组时,它会忽略类别模型上的顺序并默认为其通常的 id 顺序。
干杯。
【问题讨论】:
标签: php cakephp model associations
此外,您可以在模型的关系中设置顺序。
<?php
class Post extends AppModel {
var $hasMany = array(
'Category' => array(
'className' => 'Category',
...
'order' => 'Category.name DESC',
....
),
}?>
【讨论】:
在 cakephp 3 中使用“排序”而不是“订单”:
<?php
class Post extends AppModel {
var $hasMany = array(
'Category' => array(
'className' => 'Category',
...
'sort' => 'Category.name DESC',
....
),
}?>
【讨论】:
您可以使用 ContainableBehavior 来做到这一点:
$this->Post->find('all', array('contain' => array(
'Category' => array(
'order' => 'Category.created DESC'
)
)));
http://book.cakephp.org/view/1325/Containing-deeper-associations
【讨论】:
您可以指定find 方法参数的order 属性。否则,它将默认为最顶层/父模型的顺序。在您的情况下,Category.id。
【讨论】:
order参数。
在关联模型中按列排序需要设置sortWhitelist。
$this->paginate['order'] = [ 'Fees.date_incurred' => 'desc' ];
$this->paginate['sortWhitelist'] = ['Fees.date_incurred', 'Fees.amount'];
$this->paginate['limit'] = $this->paginate['maxLimit'] = 200;
【讨论】: