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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)