我可以在 cakephp3 的 Table 类上设置默认顺序吗 [英] Can I set the default order on the Table class on cakephp3

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆