【问题标题】:cakephp order by another model field in associationcakephp 由关联的另一个模型字段排序
【发布时间】:2012-02-28 20:01:58
【问题描述】:

关于 cakePHP 查找操作中的 orderBy 的一个简单问题。假设我有 3 个相互关联的模型。当我对我的 3 个模型中的任何一个进行 find('all') cakePHP 查询时,我得到的结果还包括来自其他 2 个模型的数据。例如,假设我的模型是:

1- User
2- School
3- Country

如果我在UsersController 里面做$this->find('all'),因为我的三个模型链接在一起,我会得到这样的结果:

Array
(
     [0] => Array
         (
              [User] => Array
                     (
                          [id] => 'the_auto_incrementing_id'
                          // other table columns 
                          [created] 'creation_date'
                          [modified] 'modification_date'
                     )
              [School] => Array
                     (
                          [id] => 'the_auto_incrementing_id'
                          // other table columns 
                          [created] 'creation_date'
                          [modified] 'modification_date'
                     )
              [Country] => Array
                     (
                          [id] => 'the_auto_incrementing_id'
                          // other table columns 
                          [created] 'creation_date'
                          [modified] 'modification_date'
                     )
         )
)

我的问题是,虽然我的 find('all') 查询是在 User 模型上发起的,但是否可以 orderBy 比如说模型 School 中的 created 字段?

如果可以的话,请告诉我

谢谢

【问题讨论】:

    标签: php cakephp cakephp-1.3 sql-order-by model-associations


    【解决方案1】:

    如果您尝试从 User、School 和 Country 获取所有相关数据,但按 School.created 排序(根据您的示例),您可以从 School 模型运行查询。

    我假设你在用户控制器中 - 如果是这样,它就是这样:

    $myData = $this->User->School->find('all', array('order'=>'School.created DESC'));
    

    (不需要加载学校模型,因为它是链接的,所以你只需通过用户模型引用它)

    【讨论】:

      猜你喜欢
      • 2022-10-16
      • 2011-11-06
      • 1970-01-01
      • 1970-01-01
      • 2017-12-24
      • 2018-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多