CakePHP 2.0: how to access properties of the parent object?

Posted by PaulJ on Stack Overflow See other posts from Stack Overflow or by PaulJ
Published on 2011-11-12T17:48:44Z Indexed on 2011/11/12 17:50 UTC
Read the original article Hit count: 153

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about cakephp

Related posts about cakephp-2.0