我可以在 cakephp3 的 Table 类上设置默认顺序吗

Can I set the default order on the Table class on cakephp3(我可以在 cakephp3 的 Table 类上设置默认顺序吗)
本文介绍了我可以在 cakephp3 的 Table 类上设置默认顺序吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在 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 类上设置默认顺序吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Codeigniter htaccess to remove index.php and www(Codeigniter htaccess 删除 index.php 和 www)
htaccess mod_rewrite part of url to GET variable(htaccess mod_rewrite url 的一部分到 GET 变量)
Replacing a querystring parameter value using mod_rewrite(使用 mod_rewrite 替换查询字符串参数值)
.htaccess in subdirectory #39;overriding#39; parent htaccess(子目录“覆盖父 htaccess 中的 .htaccess)
How to rewrite SEO friendly url#39;s like stackoverflow(如何像stackoverflow一样重写SEO友好的url)
Is it okay to have a very long .htaccess file?(有一个很长的 .htaccess 文件可以吗?)