我在两个模型之间有这种关系:
Snippet belongsTo SnippetCategory SnippetCategory hasMany Snippet
当我添加新的Snippet时,我需要一个SnippetCategories的下拉列表。为此,我有以下代码:
//Snippet.php
public $belongsTo = array(
'SnippetCategory' => array(
'className' => 'SnippetCategory',
'foreignKey' => 'snippet_category_id'));
//SnippetCategory.php
public $hasMany = array(
'Snippet' => array(
'className' => 'Snippet',
'foreignKey' => 'snippet_category_id',
'dependent' => true));
//SnippetsController.php
public function add() {
$categories = $this->Snippet->SnippetCategory->find('list');
$this->set(compact('categories'));
if ($this->request->is('post')) {
$this->request->data['Snippet']['user_id'] = $this->Auth->user('id');
if ($this->Snippet->saveAssociated($this->request->data)) {
$this->Session->setFlash('Snippet saved.');
$this->redirect(array('action' => 'index'));
}
}
}
//Snippets/add.ctp
// ...html...
echo $this->Form->input('categories', array(
'tabindex' => 2));
// ...html...
但我得到一个“对非对象调用成员函数find()”错误。我知道它必须是一些愚蠢的错误,但我无法找到我做错的事情......
拜托,有人可以帮我这个吗?提前谢谢!
答案 0 :(得分:0)
首先,您应该发布Snippet和SnippetCategory模型中的整个代码。也许有一些东西导致了这个奇怪的行为,这个行为没有在这段代码中显示出来。
错误非常简单,SnippetCategory未初始化。
您可以随时使用:
$this->loadModel('SnippetCategory');
$this->SnippetCategory->find('list');
但这不是最聪明的方式,因为必须使用Snippet模型初始化SnippetCategory模型