通过CakePHP中的belongsTo表指定订单参数 [英] Specifying order parameter through a belongsTo table in CakePHP
问题描述
假设我有两个表格:城市
和国家
。 城市
模型属于
国家/地区。现在,当我显示城市列表时,希望按国家名称然后按城市名称排序。
Let's say I've got two tables: cities
and countries
. The City
model belongsTo
a Country
. Now, when I display lists of cities, I want them to be ordered by country name and then city name.
我在我的 City中尝试过
模型类:
var $order = array('Country.name' => 'asc', 'City.name' => 'asc');
排序顺序在我的索引页上正常工作,但是在模型具有多个位置的地方出现错误要求不要加载关联的模型。更改加载的表时是否必须更改顺序参数,还是有一种更聪明的方法来做到这一点?
The sort order works correctly for my index page, but I get errors in several places where the model has been asked not to load associated models. Do I have to change the order parameters when I change which tables are loaded, or is there a smarter way to do this?
就目前而言,我认为默认订单定义为 City.name
,然后将其分别更改为 Country.name
和索引页面上的City.name
。这样,默认情况下它是安全的,而且我也不会遇到意外错误。
For now, I think I'll make the default order definition be City.name
and then just change it to Country.name
and City.name
on the index page. That way it's safe by default, and I shouldn't get unexpected errors.
更新:为建议使用Rob ,您可以在模型关联中指定订单参数。查询构建器将这样应用它们:
Update: As Rob suggested you can specify order parameters in the model associations. The query builder applies them like this:
- 如果在
order
字段上 - 按照所有相关模型的显示顺序进行遍历。如果关联包含
order
参数,请将其添加到列表的末尾。
- If there is an
order
field on the main model, apply it first. - Walk through all the associated models in the order they appear. If the association includes an
order
parameter, add it to the end of the list.
要实现我的示例,我将这样做:
To implement my example, I would do it like this:
class City extends AppModel {
var $belongsTo = array(
'Country' => array(
'order' => array('Country.name' => 'asc', 'City.name' => 'asc')));
}
一个警告:如果关闭 City.recursive
,则城市将不排序。但是,当我关闭递归时,通常只检索一条记录。
One caution: if you turn off City.recursive
, then the cities will be unsorted. However, I'm usually retrieving only one record when I've turned off recursion.
推荐答案
您是否尝试过直接定义顺序在你的协会?我从来不需要这样做,所以我不能保证它会做您想要做的事,但是:
Have you tried defining the order directly in your association? I've never needed to do this, so I can't swear it will do what you're after, but:
class City extends AppModel {
$belongsTo = array(
'Country' => array(
'Order' => 'Country.name'
)
);
}
您可以为您的国家/地区做类似的事情当然是code>模型。
这篇关于通过CakePHP中的belongsTo表指定订单参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!