cakephp 3.6从数据库获取相关数据
我是CakePHP新手,有些东西没有按预期工作 我有一个具有以下方法的PostsController: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('
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');
}