【问题标题】:Cakephp, ordering associated tablesCakephp,订购关联表
【发布时间】:2010-06-27 17:55:02
【问题描述】:

当我搜索一个“有很多”其他东西的模型时。

例如,一篇博客文章有很多类别。

在搜索具有关联类别的博客文章时,如何对关联的类别进行排序?返回数组时,它会忽略类别模型上的顺序并默认为其通常的 id 顺序。

干杯。

【问题讨论】:

    标签: php cakephp model associations


    【解决方案1】:

    此外,您可以在模型的关系中设置顺序。

    <?php
    class Post extends AppModel {
      var $hasMany = array(
        'Category' => array(
            'className' => 'Category',
            ...
            'order' => 'Category.name DESC',
            ....
        ),
    }?>
    

    【讨论】:

      【解决方案2】:

      在 cakephp 3 中使用“排序”而不是“订单”:

      <?php
      class Post extends AppModel {
        var $hasMany = array(
          'Category' => array(
              'className' => 'Category',
              ...
              'sort' => 'Category.name DESC',
              ....
          ),
      }?>
      

      【讨论】:

        【解决方案3】:

        您可以使用 ContainableBehavior 来做到这一点:

        $this->Post->find('all', array('contain' => array(
            'Category' => array(
                'order' => 'Category.created DESC'
            )
        )));
        

        http://book.cakephp.org/view/1325/Containing-deeper-associations

        【讨论】:

          【解决方案4】:

          您可以指定find 方法参数的order 属性。否则,它将默认为最顶层/父模型的顺序。在您的情况下,Category.id

          【讨论】:

          • 关联模型是在模型本身上排序的,当您在模型上关联“有很多”时,您在哪里添加它?
          • 发布您用于检索模型数据的代码或查看book.cakephp.org/view/1018/find。我相信你想设置order参数。
          • hasMany 关系意味着 2 个单独的查询 - 当您在 find 方法上设置 order 属性时,您会收到错误,因为相关模型未包含在原始查询中,因此“不存在”。
          【解决方案5】:

          在关联模型中按列排序需要设置sortWhitelist

          $this->paginate['order'] = [ 'Fees.date_incurred' => 'desc' ];
          $this->paginate['sortWhitelist'] = ['Fees.date_incurred', 'Fees.amount'];
          $this->paginate['limit'] = $this->paginate['maxLimit'] = 200;
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-12-04
            • 1970-01-01
            相关资源
            最近更新 更多