1
votes

I'm trying to link two (and more) models in a CakePHP application.

I have two database tables: clients and notes. I have the following model classes:

<?php
class Client extends AppModel {
    var $name = 'Client';
    var $hasMany = 'Note';
}

And:

<?php
class Note extends AppModel {
    var $name = 'Note';
    var $belongsTo = 'Client';
}

However, I don't think they're linking. When I run print_r($this->Client->find()); in a controller I get the following output:

Array
(
    [Client] => Array
        (
            [id] => 1
            [name] => Martin Bean
        )

)

How can I also fetch the associated Note records for each Client?

EDIT: Despite having the above in my model classes, if I place the following in a controller:

$this->Client->Behaviors->attach('Containable');
print_r($this->Client->find('all', array('contain' => 'Note')));

I get the following error message:

Warning (512): Model "Client" is not associated with model "Note" [CORE/cake/libs/model/behaviors/containable.php, line 363]

Have I missed something that isn't explained in the CakePHP cookbook?

EDIT 2: I don't know if this is any help; it's the debug output:

ContainableBehavior::containments() - CORE/cake/libs/model/behaviors/containable.php, line 363 ContainableBehavior::beforeFind() - CORE/cake/libs/model/behaviors/containable.php, line 121 ModelBehavior::dispatchMethod() - CORE/cake/libs/model/model_behavior.php, line 169 BehaviorCollection::trigger() - CORE/cake/libs/model/model_behavior.php, line 494 Model::find() - CORE/cake/libs/model/model.php, line 2108 PostsController::index() - APP/controllers/posts_controller.php, line 6 Dispatcher::_invoke() - CORE/cake/dispatcher.php, line 204 Dispatcher::dispatch() - CORE/cake/dispatcher.php, line 171 [main] - APP/webroot/index.php, line 83

3
Try clearing your model cache as well APP/tmp/cache/models - especially if you added these changes after initially creating and running these files. Sometimes it's all it takes ~Ross
Also check your (app_)model for any trace of $this->recursive - if it's less than 0 you won't get related data.Ross

3 Answers

1
votes

So just to confirm

You have two tables 'notes' and 'clients'

Both have a primary key named id

'notes' contains 'client_id'

There is correct test data, 'client' with id 1 is on several 'note' rows

Before your find() call there is not a $this->Client->recursive = -1 assignment.

Add

$var actsAs = array('Containable');

to both your Client and Note model or just add it to your app_model.php to attach the containable behaviour to every model automatically.

P.S Set debug to 2 to clear our the model cache if you have recently added a new table or amended a field.

0
votes

look up containable. $this->Client->find('all', array('contain' => array('Note')));

0
votes

Fixed it! My models' filenames were incorrect.

Instead of client.php or note.php I had saved them as client_model.php and note_model.php. All works fine now!