问题描述
在 CakePHP 2.x 中,模型中有一个属性 $order.所以我使用这个属性来对我的数据进行全局排序.例如,假设我需要在用于添加行的 Country 模型中的视图中显示一个带有国家/地区的选择框:
In CakePHP 2.x there was a property $order in Models. So I used this property to order my data globally. So for example assuming that I need to show a select box with countries on a view in my Country model used to add the line:
$order = 'Country.country DESC';
然后当我从任何控制器获取国家/地区时,数据按国家/地区名称排序,而不是按 id 或任何其他字段排序.这对选择框特别有用.在 CakePHP 3.x 上,我似乎在文档中找不到任何类似的参考.
and then when I fetched the countries from any controller the data where ordered by the country name and not by the id or any other field. This was very helpful specially for the select boxes. On CakePHP 3.x I can't seem to find any similar reference at the documentation.
有什么办法可以让我在获取数据时对数据进行全局排序,而不是在每次查找中使用 order 选项?
Is there anything that I can do to have my data sorted globally when I fetch them and not use the order option in each find?
推荐答案
只需添加您心爱的属性并使用 beforeFind() 回调 Table 对象中的值从属性添加到查询中.
Just add your beloved property back and use the beforeFind() callback in the Table object to add the value from the property to the query.
或者只是创建自定义查找器:
public function findOrdered(Query $query, $options) {
return $query->order([
$this->alias() . '.name' => 'ASC'
]);
}
并使用它
$this->find('list')->find('ordered')->all();
或者创建一个有序列表 find 来返回整个有序列表.
Or create an ordered list find that returns the whole ordered list.
public function findOrderedList(Query $query, $options) {
return $this->findList($query, $options)
->order([
$this->alias() . '.name' => 'ASC'
]);
}
或者直接重载 findList() 方法并调用父级.
Or overload the findList() method directly and call the parent.
或者如果您的 find() 通过关系被调用,您可以 使用 sort 选项设置关系的默认顺序.
Or if your find() gets called via a relationship, you can set the default order for the relationship by using the sort option.
$this->hasMany('AuditLogs', [
'sort' => [
'AuditLogs.timestamp' => 'desc',
],
]);
这篇关于我可以在 cakephp3 的 Table 类上设置默认顺序吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!



大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)