0
votes

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?

1
I have never used the habtm alias tables but shouldn't your contain consist of an array of models? 'contain' => array('ProductRelation')Tim Joyce
Do you have this in your AppModel: var $actsAs = array( 'Containable' );Barry Chapman
@BarryChapman He says he does.Tim Joyce
'contain' does not need to be an array, It is cast as an array here github.com/cakephp/cakephp/blob/master/lib/Cake/Model/Behavior/…dogmatic69
@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

1 Answers

2
votes

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.