問(wèn)題描述
在 CakePHP 2.x 中,模型中有一個(gè)屬性 $order
.所以我使用這個(gè)屬性來(lái)對(duì)我的數(shù)據(jù)進(jìn)行全局排序.例如,假設(shè)我需要在用于添加行的 Country
模型中的視圖中顯示一個(gè)帶有國(guó)家/地區(qū)的選擇框:
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';
然后當(dāng)我從任何控制器獲取國(guó)家/地區(qū)時(shí),數(shù)據(jù)按國(guó)家/地區(qū)名稱排序,而不是按 id
或任何其他字段排序.這對(duì)選擇框特別有用.在 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.
有什么辦法可以讓我在獲取數(shù)據(jù)時(shí)對(duì)數(shù)據(jù)進(jìn)行全局排序,而不是在每次查找中使用 order 選項(xiàng)?
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?
推薦答案
只需添加您心愛(ài)的屬性并使用 beforeFind() 回調(diào) Table 對(duì)象中的值從屬性添加到查詢中.
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.
或者只是創(chuàng)建自定義查找器:
public function findOrdered(Query $query, $options) {
return $query->order([
$this->alias() . '.name' => 'ASC'
]);
}
并使用它
$this->find('list')->find('ordered')->all();
或者創(chuàng)建一個(gè)有序列表 find 來(lái)返回整個(gè)有序列表.
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() 方法并調(diào)用父級(jí).
Or overload the findList() method directly and call the parent.
或者如果您的 find()
通過(guò)關(guān)系被調(diào)用,您可以 使用 sort
選項(xiàng)設(shè)置關(guān)系的默認(rèn)順序.
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',
],
]);
這篇關(guān)于我可以在 cakephp3 的 Table 類上設(shè)置默認(rèn)順序嗎的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!