CakePHP - 使用HABTM连接表字段进行排序

时间:2010-05-14 21:35:36

标签: php arrays cakephp

这是我的问题:

表1:帖子

id - int
title - varchar

表2:类别

id - int
name - varchar

HABTM JoinTable:categories_posts

id - int
post_id - int
category_id - int
postorder - int

如您所见,连接表包含一个名为“postorder”的字段 - 这是用于对特定类别中的帖子进行排序。例如,

Posts: Post1, Post2, Post3, Post4
Categories: Cat1, Cat2
Ordering:
     Cat1 - Post1, Post3, Post2
     Cat2 - Post3, Post1, Post4

现在在CakePHP中,

$postpages = $this->Post->Category->find('all');

给了我一个像

这样的数组
Array
(
  [0] => Array
    (
      [Category] => Array
        (
          [id] => 13
          [name] => Cat1
        )
        [Post] => Array
        (
          [0] => Array
          (
            [id] => 1
            [title] => Post2
            [CategoriesPost] => Array
            (
              [id] => 17
              [post_id] => 1
              [category_id] => 13
              [postorder] => 3
            )
          )
          [1] => Array
          (
            [id] => 4
            [title] => Post1
            [CategoriesPost] => Array
            (
              [id] => 21
              [post_id] => 4
              [category_id] => 13
              [postorder] => 1
            )
          )

        )
    )
) 

如您所见[Post],它们不是根据[CategoriesPost] .postorder排序的,而是根据[CategoriesPost] .id排序。如何根据[CategoriesPost] .postorder获取数组?

提前感谢您的时间:)

更新1: Cake的SQL Log中的查询是:

SELECT `Category`.`id`, `Category`.`name` FROM `categories` AS `Category` WHERE 1 = 1

SELECT `Post`.`id`, `Post`.`title`, `CategoriesPost`.`id`, `CategoriesPost`.`post_id`, `CategoriesPost`.`category_id`, `CategoriesPost`.`postorder` FROM `posts` AS `Post` JOIN `categories_posts` AS `CategoriesPost` ON (`CategoriesPost`.`category_id` IN (13, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52) AND `CategoriesPost`.`post_id` = `Post`.`id`) 

我正在寻找的是如何在第二个SELECT SQL查询中将蛋糕放入Order By CategoriesPost.postorder。

更新2: 尝试使用以下订单

$this->Post->Category->find('all',array('order'=>array('postorder'=>'ASC')));

抛出SQL错误

SQL Error: 1054: Unknown column 'PostsCategory.postorder' in 'order clause'

SQL查询

SELECT `Category`.`id`, `Category`.`name` FROM `categories` AS `Category` WHERE 1 = 1 ORDER BY `CategoriesPost`.`postorder` ASC

而不是第二个SQL查询中的ORDERBY(在我的update1中),它在第一个SQL查询中执行,如上所示。

1 个答案:

答案 0 :(得分:4)

尝试将其作为协会的一部分:

var $hasAndBelongsToMany = array(
    'Post' => array(
        ...
        'order' => 'CategoriesPost.postorder DESC',
    )
)

这可能有效,也可能无效,尚未经过测试。