0

First time using Cake and its containable behaviour, but it's not working as expected ... or at all.

I'm trying to obtain a list of accessories for a product. Product model HABTM products (alias 'ProductRelation'). Join table is products_products which has two product ids - product_id and related_id. It's against this I want to pull the list of accessories (products driven from the related_id column) for a given product_id

In my Product model, I've added $actsAs = array('Containable');

And in my controller, a quick test of containable using reference from the cookbook fails to contain products at all, even without conditions.

debug($this->Product->find('all', array('contain' => 'ProductRelation')));

.. returns an array of every product in the db, with ALL related models - images, content tabs, ratings, reviews, pricing, etc I haven't tried applying any 'conditions' against this because the call as written should limit data to the product and it's ProductRelation data, according to the cookbook ...

Any tips?

tremendusapps
  • 108
  • 1
  • 13
  • I have never used the habtm alias tables but shouldn't your contain consist of an array of models? `'contain' => array('ProductRelation')` – Tim Joyce Dec 07 '12 at 13:01
  • 1
    Do you have this in your AppModel: `var $actsAs = array( 'Containable' );` – Barry Chapman Dec 07 '12 at 13:28
  • 1
    @BarryChapman He says he does. – Tim Joyce Dec 07 '12 at 14:11
  • 1
    'contain' does not need to be an array, It is cast as an array here https://github.com/cakephp/cakephp/blob/master/lib/Cake/Model/Behavior/ContainableBehavior.php#L106 – dogmatic69 Dec 07 '12 at 14:27
  • @TimJoyce - let me refer to what he said: `In my Product model, I've added $actsAs = array('Containable');` He has it on `Product` model. I stated to add it in the AppModel - since `Containable` needs to be active on the model being contained, and not simply the one doing the containing. Adding it to `AppModel` will naturally make it available to all models inheriting `AppModel`. – Barry Chapman Dec 07 '12 at 16:51
  • The model he is trying to contain is `ProductRelation`. – Barry Chapman Dec 07 '12 at 16:51

1 Answers1

2

It seems like you have recursive on. Try using the following:

debug($this->Product->find('all', array(
    'contain' => 'ProductRelation',
    'recursive' => -1
)));

If that works for you, you should start adding containable to the AppModel class and setting the recursive property to -1. This will ensure you only ever get the results you request.

NB: Cake does not join for HABTM, so you can not use ProductRelation in any conditions.

dogmatic69
  • 7,574
  • 4
  • 31
  • 49
  • " Cake does not join for HABTM, so you can not use ProductRelation in any conditions." . dead on, thanks. I worked around it with Joins and running conditions on these. I suppose this seems to be right from other posts. – tremendusapps Dec 10 '12 at 22:54