2012-03-30 44 views
0

我有以下型號:如何調用read時取CakePHP中填充關聯模型()

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)!==false; 
    } 
} 

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); 
    } 

} 

在我的控制,我做這樣的事情:

$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.'); 
} 

我注意到在Item->canView()$this->data['Site']填充了來自站點tabl的列數據即但它僅僅是一個數組而不是一個對象。

另一方面$this->Site是一個站點對象,但它尚未填充來自站點表的列數據,如$this->data

讓CakePHP獲得關聯模型作爲對象(所以我可以調用它的方法)幷包含數據的正確方法是什麼?或者,我是否全力以赴?

謝謝!

回答

0

「...並用找到的記錄設置當前模型數據(Model :: $ data)。」 from http://api13.cakephp.org/class/model#method-Modelread

+0

我可以使用'$ this-> data'中的foreignKey id調用'$ this-> Site-> read()',但這會導致額外的數據庫查詢被執行,對吧?這似乎是不必要的,因爲我已經有了'$ this-> data ['Site']'中的數據,它只是沒有分配給對象。我也許也可以設置'$ this-> Site'的'$ data'成員,因爲我已經擁有了這些數據,但是這似乎是一種處理它的方式。 – 2012-04-01 21:33:15