CakePHP 2.0: how to access properties of the parent object?
- by PaulJ
I just started learning CakePHP 2.0 a few days ago, and there's one thing that is leaving me stumped: say I have an User model and a Posts model:
class User extends AppModel {
public $name = "User";
public $hasMany=array(
'Post' => array(
'className' => 'Post',
'foreignKey' => 'author_id'
)
);
}
class Post extends AppModel {
public $name = 'Post';
public $belongsTo = array(
'className' = 'User',
'foreignKey' = 'author_id',
);
}
(Where "author_id" is the foreign key in the posts table that references the Users table's primary key).
And now, in the PostsController, I want to access the properties of the user that owns the current post (to show his display name, for example). What would be the proper syntax? I tried:
$this->Post->User->find('first', array('conditions' => array('User.id' => "$usuario")))
But it didn't work (I guess it's because the User is the parent of the Post object, not its child). Or should CakePHP load everything automatically, once you've declared the $hasMany and $belongsTo relationships?