Cakephp 错误:在布尔值上调用成员函数newEntity()

Cakephp 错误:在布尔值上调用成员函数newEntity(),cakephp,Cakephp,我是cakephp新手。我已经完成了所有必需的步骤,但在使用cakephp将数据保存到数据库中时仍然遇到问题 Articlecontroller.php中adduser函数的代码: public function adduser() { $user = $this->Users->newEntity(); if ($this->request->is('post')) { $user = $this->Users->patchE

我是cakephp新手。我已经完成了所有必需的步骤,但在使用cakephp将数据保存到数据库中时仍然遇到问题

Articlecontroller.php中adduser函数的代码:

public function adduser()
{
    $user = $this->Users->newEntity();
    if ($this->request->is('post')) {
        $user = $this->Users->patchEntity($user, $this->request->getData());

        // Hardcoding the user_id is temporary, and will be removed later
        // when we build authentication out.
        $user->user_id = 1;

        if ($this->Users->save($user)) {
            $this->Flash->success(__('Your article has been saved.'));
            return $this->redirect(['action' => 'index']);
        }
        $this->Flash->error(__('Unable to add your article.'));
    }
    $this->set('article', $user);
}
UserTable模型的代码:

<?php
// src/Model/Table/ArticlesTable.php
namespace App\Model\Table;

use Cake\ORM\Table;

class UsersTable extends Table
{
    public function initialize(array $config)
    {
        $this->addBehavior('Timestamp');
    }
}

我想您忘记在控制器中加载用户模型了。在函数adduser()中将这一行添加到第一行之前应该是固定的。应该是这样的

public function adduser()
{
    $this->loadModel('Users');
    $user = $this->Users->newEntity();
...
Cakephp文档。

嗯,您需要有一个使用该插件的CakePHP应用程序。您需要添加$this->loadComponent('Auth');要初始化AppControllers()方法并正确配置它


我强烈建议您完成官方CakePHP文档的完整博客教程,否则您将不会对框架中的任何插件或任何其他内容感兴趣。它还包括设置Auth。

由于其他已开始,当不在与您正在访问的表相关的控制器中时,您需要加载模型及其相关实体

当前检索表的方法是通过表注册表,如下所示:

use Cake\ORM\TableRegistry;

// Now $articles is an instance of our ArticlesTable class. This is how CakePHP 4 prefers it.
$articles = TableRegistry::getTableLocator()->get('Articles');

// Prior to 3.6.0
$articles = TableRegistry::get('Articles');
因此,对于公共方法,它应该如下所示:

public function adduser()
{
    $usersTable = TableRegistry::getTableLocator()->get('Users');
    $user = $usersTable->newEntity();

    if ($this->request->is('post')) {
      ...code for handling post...
    }
 }
。虽然
$this->loadModel('Articles')
有效,但快速搜索文档表明,ORM部分和示例中都不经常提到它