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

查看:132
本文介绍了我可以在cakephp3上的Table类上设置默认顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在CakePHP 2.x中,在模型中有一个属性 $ order 。所以我使用这个属性来命令我的数据全局。例如,假设我需要在我的国家模型中显示一个国家/地区的选择框,用于添加行:

  $ order ='Country.country DESC'; 

然后当我从任何控制器获取国家时,数据由国家名称而不是 id 或任何其他字段。这是非常有用的特别为选择框。在CakePHP 3.x上我在文档中似乎找不到任何类似的引用。



当我抓取时,我可以做些什么来让我的数据全局排序

解决方案

只需添加您的心爱的属性,并使用 beforeFind()回调在Table对象中添加属性的值到查询。



或只是 create a custom finder

  public function findOrdered Query $ query,$ options){
return $ query-> order([
$ this-> alias()。'.name'=>'ASC'
]) ;
}

并使用

  $ this-> find('list') - > find('ordered') - > all 

或创建一个有序列表查找返回整个有序列表。

  public function findOrderedList(Query $ query,$ options){
return $ this-> findList($ query,$ options)
- > order([
$ this-> alias()。'.name'=>'ASC'
]);
}

或直接重载findList()方法并调用父项。 >

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';

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.

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?

解决方案

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.

Or just create a custom finder:

public function findOrdered(Query $query, $options) {
    return $query->order([
        $this->alias() . '.name' => 'ASC'
    ]);
}

And use it

$this->find('list')->find('ordered')->all();

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'
    ]);
}

Or overload the findList() method directly and call the parent.

这篇关于我可以在cakephp3上的Table类上设置默认顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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