Wizard
Wizard

Reputation: 11295

CakePHP join model and its own relationships

In Shop model I have:

public $belongsTo = array(
    'Company' => array()
);

Model Company has its own relationships defined in its model class. How can I fetch Company relation when performing:

$this->Shop->find('all',
       array(
           'conditions' => array(
               'Shop.loyaltycard' => 0,
            )
       )
);

Upvotes: 1

Views: 56

Answers (2)

Inigo Flores
Inigo Flores

Reputation: 4469

If you have properly declared the relationships,find() will automatically fetch the first level of associated models, provided you haven't altered the default level of recursion (which is 1).

If it fails, try the following:

$this->Shop->recursive=1;
$this->Shop->find('all',array(
    'conditions' => array(
        'Shop.loyaltycard' => 0,
    )
));

More on Model attribute recursive.

Another option is to load the Containable behavior, which will allow you to filter which relationships you wish to fetch.

$this->Shop->Behaviors->load('Containable'); //or make your model act as Containable 
$this->Shop->contain('Company');
$this->Shop->find('all',array(
    'conditions' => array(
        'Shop.loyaltycard' => 0,
    )
));

More on ContainableBehavior.

Also, please modify your relationship declaration to the following:

public $belongsTo = array(
    'Company'
);

Not sure how the empty array affects your relationship, but it may cause it to fail. Please note that this will only work if you have followed CakePHP conventions.

Upvotes: 1

Max90
Max90

Reputation: 193

If you don't want to find all related model but just Company you can add $actsAs = array('Containable'); in your shop model and then do the search like this:

$this->Shop->find('all',array(
    'conditions' => array(
        'Shop.loyaltycard' => 0,
    ),'contain' => array(
         'Company'
));

See cakephp containable http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html

Upvotes: 0

Related Questions