CakePHP - HABTM Sort Join Table Field

here is my problem:

Table 1: Messages

id - int title - varchar 

Table 2: Categories

 id - int name - varchar 

HABTM JoinTable: categories_posts

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

As you can see, the connection table contains the "postorder" field - this is for organizing messages in a specific category. For instance,

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

Now in CakePHP,

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

gives me an array like

 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 ) ) ) ) ) 

As you see [Post], they are not ordered according to [CategoryPost] .postorder, but are ordered according to [CategoryPost] .id. How can I get an array ordered according to [CategoryPost] .postorder?

Thank you in advance for your time :)

Update 1: Queries from SQL Cake 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`) 

What I'm looking for is how to make a cake to order by Post.postorder categories in a second SELECT SQL query.

Update 2: Trying to use order by following

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

causes an SQL error

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

SQL Query -

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

Instead of ORDERBY in the second SQL query (in my update1), it is retrieved in the first SQL query, as shown above.

+4
source share
1 answer

Try to make this part of the association:

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

This may or may not work, have not tested it.

+3
source

Source: https://habr.com/ru/post/1309824/


All Articles