Search code examples
phpcakephpmodel-bindingcakephp-modelcontainable

Deep Associations works with recursive => 2 but too slow to load


I have 3 models Product having product_family_id as foreign key to ProductFamily and ProductFamily have customer_id as foreign key to Customer. Putting recursive to 2 in Product model allow me to get Customer name from Customer for a product. But its too slow as data is vast

Tried Using Bind model as below. Didn't worked for me. Using Cakephp framework.

$this->Product->bindModel(array(
'belongsTo' => array(
               'ProductFamily' => array(
                   'foreignKey' => false,
                   'conditions' => 
                        array('Product.product_family_id = ProductFamily.id')
                   ),
               'Customer' => array(
                   'foreignKey' => false,
                   'conditions' => 
                        array('ProductFamily.customer_id = Customer.id')
                   )
               )
           )); 

Solution

  • Use Containable

    The Containable behaviour will help you get exactly the data you want without the overhead of recursive 2

    set it in your AppModel to make it apply to all models at once and read up on the docs on how to use it

    class AppModel extends Model {
    
        public $actsAs = array('Containable');
        public $recursive = -1;
    }
    

    For some interfaces in your application, you may not need that much information from the model. One thing the ContainableBehavior does is help you cut down on what find() returns.

    It is possbible to only set this on the models where you would use it and set recursive to -1 right before your find (in wich you would use 'contain') but it is in my eyes a best practise to do this for all models