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

Ama*_*eep 2 cakephp

我是cakephp的新手.我已经完成了所有必需的步骤,但仍然无法使用cakephp在数据库中保存数据

adicser函数代码来自Articlecontroller.php:

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);
}
Run Code Online (Sandbox Code Playgroud)

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');
    }
}
Run Code Online (Sandbox Code Playgroud)

数据库表到我的locahost: 在此输入图像描述

exp*_*cki 6

我想你忘了在控制器中加载用户模型了.应该修复在第一行之前在函数adduser()中添加这一行.它看起来应该是这样的.

public function adduser()
{
    $this->loadModel('Users');
    $user = $this->Users->newEntity();
...
Run Code Online (Sandbox Code Playgroud)

Cakephp文档. https://book.cakephp.org/3.0/en/controllers.html#loading-additional-models