vibha
vibha

Reputation: 129

cakephp: hasMany not working

device.php:

var $hasOne = array(        
        'Monitordevice' => array(
            'className' => 'Monitordevice',
            'foreignKey' => 'deviceId', // 'deviceId'
            'conditions' => '',     
        )
    ); 

    var $hasMany = array(   
        'CreativeSchedule' => array(
                    'className' => 'CreativeSchedule',
                    'foreignKey' => 'deviceId',
                    'conditions' => '',     

                    )

    );

creative_schedules.php

var $belongsTo = array(
        'Device' => array(
            'className' => 'Device',
            'foreignKey' => 'deviceId',
                    'conditions' => '',     
        )
    );

when I call this:

$all_devices=$this->Device->CreativeSchedule->find('all');

device table is not making any join with creative_schedules

instead I get 2 queries:

SELECT `Device`.`id`, ....FROM `devices` AS `Device` LEFT JOIN `monitordevices` AS `Monitordevice` ON (`Monitordevice`.`deviceId` = `Device`.`id`) 

AND

SELECT `CreativeSchedule`.`id`, ....FROM `creative_schedules` AS `CreativeSchedule` WHERE `CreativeSchedule`.`deviceId` IN (1, 2, 3, 4, 5, 6, 7) 

Upvotes: 1

Views: 2373

Answers (1)

MichaelC
MichaelC

Reputation: 293

Use Containable.

In both of these classes, add:

var $actsAs = array( 'Containable' );

Then your find should look like:

$all_devices = $this->Device->CreativeSchedule->find('all', 'contain' => array('Device'));

As a side note, I'm not sure where you're putting the find(), and if that controller uses CreativeSchedule, but consider just $this->CreativeSchedule->find(...) if you can, as model chaining can lead to reduced performance, and it does not "link" the queries together through their associations. (Which I'm not sure if you were assuming or not.)

At worse case scenario, you could always put $this->loadModel('CreativeSchedule') at the top of the controller action if you would like.

Upvotes: 1

Related Questions