1
votes

I am using cakephp containable to retrieve related models

$this->Order->find('first',
      array(
          'conditions'=>$conditions,
          'contain' => 
              array(
                 'OrderItem'=>array(
                     'Item'=>
                         array(
                            'order' => array('Item.item_number ASC')
                          )
                   ), 
             'Location','Campaign', "Customer")     
            )
       );

I'm using this to generate an invoice, and would like to have the items sorted by item_number.

But for some reason the sort isn't working.

Any ideas?

The SQL generated is very long. but you can see the issue from this snippet that the order by is in the wrong query - - ie in the Item which is being select by id -- only one item. (And there is a seperate query for each item in the order. )

  SELECT `OrderItem`.`order_id`, `OrderItem`.`item_id`,
 `OrderItem`.`quantity`,  `OrderItem`.`id` FROM `order_items` AS `OrderItem` WHERE
 `OrderItem`.`order_id` = (3144)

And

  SELECT `Item`.`id`, `Item`.`campaign_id`, `Item`.`item_number`, `Item`.`description`,
  `Item`.`order_unit`, `Item`.`order_price`, `Item`.`maxQuantity`, `Item`.`sale_unit`,
  `Item`.`sale_price`, `Item`.`approx`, `Item`.`min_weight`, `Item`.`max_weight`,
  `Item`.`avail`, `Item`.`filename` FROM `items` AS `Item` WHERE `Item`.`id` = 122 
 ORDER    BY `Item`.`item_number` ASC

What I would like to see is the first query do a inner join Items.id on OrderItem.item_id and order that query by item_number, but I see that containable generates separate queries for each related model.

2
I ended up just creating a usort function to sort the OrderItems.....josephtikva1

2 Answers

1
votes

Make sure you have added:

var $actsAs = array('Containable');

to the Model, or

$this->Order->Behaviors->attach('Containable');

to the action. It isn't clear from your post if you have this already.

Also you should elaborate on isn't working - what isn't? Unexpected results? nothing at all?

0
votes

You might want to try Linkable instead:

https://github.com/Terr/linkable