John
John

Reputation: 17

CakePHP 2.1.1. containable behaviour not working

i'm using cakephp 2.1.1. this is my tables associations: x hasmany y hasmany z hasmany w.

everything is correctly setup i think but when i make this query:

$conditions = array(
'contain' => array(
'y' => array (
            'z' => array(
                'w'=> array(
                    'conditions' => array('col>=' => $q))
     )
 )
 ));

$this->loadmodel('x');
 $o=$this->x->find('all',$conditions);//array(
 debug($o);

i dont have the result which i want; only table x is fetched! why? for example this is my model x php code which is similar to others:

 <? php

class x extends AppModel
{
    var $name='x';
    public $actsAs = array('Containable');
    public $hasMany = array( 'y');
}

maybe cakephp version? thanks!

info: i want to make statement like this:

select z.col1, y.col2, x.col3
from z, y, x, w
where  w.col>= 3
and w.z_id = z.id
and z.y_id = y.id
and z.x_id = x.id

Upvotes: 0

Views: 1175

Answers (1)

David Yell
David Yell

Reputation: 11855

There are quite a few points here.

Firstly, if the Behaviour isn't working, it's probably not bet to assume anything, least of all that everything is fine! ;)

I assume that you've stripped a large amount of code out, as your relationships don't have any foreign keys defined which is pretty critical if Cake is to link up your models.

Not sure why you are using loadModel() as this kind of thing should be done in Model X's controller or the X Model. So you shouldn't have to load the model. If your associations are working properly the Contain will load the models as it goes along.

As for your expected SQL statement, unfortunatly Containable does not join models like this, and will join a few models, but if you have hasMany it will run a series of SELECT statements to get additional data and then join it all together.

It also uses a LEFT JOIN rather than your expected CROSS JOIN. This can be configured in the options of Containable though, or you can instantiate a new db object and create a subquery.

To return to your problem,

  • I would first check the model associations here.
  • I would read up on the Book to see if you are creating the associations properly. http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasmany
  • I would also ensure that your actual database schema is correct. Your foreign keys are following naming conventions or are defined in the model.
  • I would try backing up my model files and using the Cake Console to cake bake model and see if the baked models will Contain properly.

Hope this gives you a starting spot, if you haven't already solved this of course!

Upvotes: 1

Related Questions