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
Fixed it! My models’ filenames were incorrect.
Instead of
client.phpornote.phpI had saved them asclient_model.phpandnote_model.php. All works fine now!