3

我想我有一个安静的简单错误,但我无法解决它......我尝试关联两个表:

  • 项目有很多关键词
  • 关键字belogsTo项目

我的代码:

<?php
class KeywordsController extends AppController{
    public function add(){
        $projects = $this->Keyword->Project->find('list'); //***here is the error***
        //pr($projects);

        if ($this->request->is('post')) {
            $this->Keyword->save($this->request->data);
            $this->redirect('/keywords');   
        }
    }
}

<?php
class ProjectsController extends AppController{
    public function add(){
        if ($this->request->is('post')) {
            $this->Project->save($this->request->data);
            $this->redirect('/projects');   
        }
    }
}

<?php
class Project extends AppModel{
    public $hasMany = 'Keyword';
}

<?php
class Keyword extends AppModel{
    public $belongsTo = 'Project';

}

错误信息:

错误:在非对象
文件上调用成员函数 find():/Users/me/Localhost/cakephp/app/Controller/KeywordsController.php
行:7

4

1 回答 1

7

在模型的类声明上方添加以下行。

App::uses('AppModel', 'Model');

还定义name类定义的属性。

public $name = 'Project';
public $name = 'Keyword';

对于项目模型

<?php
App::uses('AppModel', 'Model');
class Project extends AppModel{
    public $name = 'Project';
    public $hasMany = 'Keyword';
}

对于关键字模型

<?php
App::uses('AppModel', 'Model');
class Keyword extends AppModel{
    public $name = 'Keyword';
    public $belongsTo = 'Project';

}

编辑

$this->loadModel('Project');
$projects = $this->Project->find('list');
于 2013-09-10T09:10:14.613 回答