How to fetch populated associated models in CakePHP when calling read()

Posted by Code Commander on Stack Overflow See other posts from Stack Overflow or by Code Commander
Published on 2012-03-30T23:27:00Z Indexed on 2012/03/30 23:29 UTC
Read the original article Hit count: 253

Filed under:
|
|
|

I have the following Models:

class Site extends AppModel {
    public $name = "Site";
    public $useTable = "site";
    public $primaryKey = "id";
    public $displayField = 'name';

    public $hasMany = array('Item' => array('foreignKey' => 'siteId'));

    public function canView($userId, $isAdmin = false) {
        if($isAdmin) { return true; }
        return array_key_exists($this->id, $allowedSites);
    }
}

and

class Item extends AppModel {
    public $name = "Item";
    public $useTable = "item";
    public $primaryKey = "id";
    public $displayField = 'name';
    public $belongsTo = array('Site' => array('foreignKey' => 'siteId'));

     public function canView($userId, $isAdmin = false) {
        // My problem appears to be the next line:
        return $this->Site->canView($userId, $isAdmin);
    }

 }

In my controller I am doing something like this:

$result = $this->Item->read(null, $this->request->id);

// Verify permissions
if(!$this->Item->canView($this->Session->read('userId'), $this->Session->read('isAdmin'))) {
    $this->httpCodes(403);
    die('Permission denied.');
}

I notice that in Item->canView() $this->data['Site'] is populated with the column data from the site table. But it merely an array and not an object.

On the other hand $this->Site is a Site object, but it has not been populated with the column data from the site table like $this->data.

What is the proper way to have CakePHP get the associated model as the object and containing the data? Or am I going about this all wrong?

Thanks!

© Stack Overflow or respective owner

Related posts about php

Related posts about oop