emersonthis
emersonthis

Reputation: 33398

CakePHP: Model->Model->find()

This is a really basic question but it's not explained in the book.

What exactly happens when you sting together multiple models before the find method?

Ex: $stuff = $this->Article->User->find('all');

How is this different than: $this->User->Article->find('all');

Can you do more than two? $this->Book->Chapter->Author->find('all');

It's clear that it has something to do with the relationships between the models, but I thought those were defined in the models, so I'm not clear what's going on.

Upvotes: 1

Views: 945

Answers (1)

Reactgular
Reactgular

Reputation: 54821

When you set an association on a Model. CakePHP instantiates it at runtime and sets it as an Object property for that model.

class User extends AppModel
{
      public $hasMany = array('Document');
}

class Document extends AppModel
{
}

In the above example. User objects will contain a property called Document, but Document will not contain User.

class UsersController extends AppController
{
     public $uses = array('User');

     public function index()
     {
           $this->User-find(...); // works
           $this->User->Document->find(..); // works, because of the hasMany

           $document = ClassRegistry::init('Document');
           $document->User->find(...); // does not work, not associated to User.
     }
}

Also, keep in mind that the name of the property is the alias for the association. Not the name of the model.

class User extends AppModel
{
      public $hasMany = array(
           'Paper'=>array('className'=>'Document')
      );
}

class Document extends AppModel
{
}

This changes the property name to Paper

$this->User->Paper->find(..); // works as alias

Uses aliases on associations allows you to apply find conditions so that they generate different results.

class User extends AppModel
{
      public $hasMany = array(
           'Paper'=>array('className'=>'Document','conditions'=>array(....)),
           'Resume'=>array('className'=>'Document','conditions'=>array(....))
      );
}

That would create two properties for User models like so.

$this->User->Paper->find(..); // works as alias
$this->User->Resume->find(..); // works as alias

But, the conditions only apply when performing a find on the User model.

Upvotes: 5

Related Questions