Cakephp,对关联表进行排序
当我搜索一个“有很多”其他东西的模型时 例如,一篇博客文章有许多类别 在搜索具有关联类别的博客文章时,如何对关联类别进行排序?返回数组时,它会忽略类别模型上的顺序,并默认为其通常的id顺序Cakephp,对关联表进行排序,php,cakephp,model,associations,Php,Cakephp,Model,Associations,当我搜索一个“有很多”其他东西的模型时 例如,一篇博客文章有许多类别 在搜索具有关联类别的博客文章时,如何对关联类别进行排序?返回数组时,它会忽略类别模型上的顺序,并默认为其通常的id顺序 干杯。您可以指定find方法参数的order属性。否则,它将默认为最顶层/父模型的顺序。在您的示例中,Category.id您可以使用ContaineableBehavior执行此操作: $this->Post->find('all', array('contain' => array(
干杯。您可以指定
find
方法参数的order
属性。否则,它将默认为最顶层/父模型的顺序。在您的示例中,Category.id
您可以使用ContaineableBehavior执行此操作:
$this->Post->find('all', array('contain' => array(
'Category' => array(
'order' => 'Category.created DESC'
)
)));
此外,您可以在模型的关系中设置顺序
<?php
class Post extends AppModel {
var $hasMany = array(
'Category' => array(
'className' => 'Category',
...
'order' => 'Category.name DESC',
....
),
}?>
在cakephp 3中使用“排序”而不是“顺序”:
<?php
class Post extends AppModel {
var $hasMany = array(
'Category' => array(
'className' => 'Category',
...
'sort' => 'Category.name DESC',
....
),
}?>
在关联模型中按列排序需要设置sortWhitelist
$this->paginate['order'] = [ 'Fees.date_incurred' => 'desc' ];
$this->paginate['sortWhitelist'] = ['Fees.date_incurred', 'Fees.amount'];
$this->paginate['limit'] = $this->paginate['maxLimit'] = 200;
关联的模型是在模型本身上排序的,你在哪里添加它?当你在一个模型上获得关联的“有很多”时,找到它?发布你用来检索模型数据或查看的代码。我相信您需要设置order
参数。hasMany关系意味着两个单独的查询-当您在find方法上设置order属性时,您会得到一个错误,因为关联模型未包含在原始查询中,因此“不存在”。