2012-12-13 25 views
19

如何在CakePHP的組件中使用模型?在組件中使用模型

在控制器,你可以使用

public $uses = array(...); 

但並不在一個部件的工作方式。

什麼?

回答

32

試試這個代碼:

$model = ClassRegistry::init('Yourmodel'); 

簡單的查詢與您的模型到組件

$result= $model->find('all'); 
+0

這個作品,謝謝你,你是 – AgeDeO

+0

welocome @LucPrevoo –

+0

更好'Yourmodel'(大寫) – mark

13

你可以這樣來做:

$this->ModelName = ClassRegistry::init('ModelName'); 

但它是假設你不不使用組件內的模型。

+0

爲什麼你的建議不使用內部組件模型? –

+0

當您在組件中開始使用多個模型時,最好使用一個行爲。 – Alvaro

+2

它總是取決於具體的用例。但這個問題並沒有透露太多。 – mark

2

如果您需要當前模型,則可以使用組件的initialize()startup()回調。

public function initialize(Controller $controller) { 
    $this->Controller = $controller; 
    $this->Model = $this->Controller->{$this->Controller->modelClass}; 
    $this->modelAlias = $this->Model->alias; 
    parent::initialize($controller); 
} 

現在,您可以在組件中的任何地方訪問模型。

public function countAllItems() { 
    return $this->Model->find('count'); 
}