Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
cakephp 3.6从数据库获取相关数据_Php_Cakephp 3.0 - Fatal编程技术网

cakephp 3.6从数据库获取相关数据

cakephp 3.6从数据库获取相关数据,php,cakephp-3.0,Php,Cakephp 3.0,我是CakePHP新手,有些东西没有按预期工作 我有一个具有以下方法的PostsController: public function index() { $posts = $this->Posts->find('all'); $this->set(compact('posts'); } 但如果我尝试从另一个表/模型获取数据,如: public function index() { $posts = $this->Posts->find('

我是CakePHP新手,有些东西没有按预期工作

我有一个具有以下方法的PostsController:

public function index()
{
    $posts = $this->Posts->find('all');
    $this->set(compact('posts');
}
但如果我尝试从另一个表/模型获取数据,如:

public function index()
{
    $posts = $this->Posts->find('all');
    $categories = $this->Categories->find('all');

    $this->set(compact('posts', 'categories');
}
这将导致以下错误:

对布尔函数的成员函数find()的调用

我错过了什么


我在您的
PostsController
中使用CakePHP版本3.6.3

$this->Posts
是自动初始化的,但
$this->Categories
不是。假设文章和类别是关联的,您可以使用
$this->Posts->Categories->find()
。如果没有,您可以在PostsController中使用
TableRegistry::get('Categories')->find()

仅加载Posts模型,您还必须加载Categories模型

public function index()
{
    $posts = $this->Posts->find('all');
    $categories = $this->loadModel('Categories')->find('all');

    $this->set(compact('posts', 'categories');
}