编程语言
首页 > 编程语言> > CakePHP关联错误:在非对象上调用成员函数find()

CakePHP关联错误:在非对象上调用成员函数find()

作者:互联网

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

>项目有很多关键字
>关键词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';

}

错误信息:

Error: Call to a member function find() on a non-object
File:
/Users/me/Localhost/cakephp/app/Controller/KeywordsController.php
Line: 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');

标签:php,cakephp,associations
来源: https://codeday.me/bug/20190728/1565820.html