Cod*_*rer 10 php model-view-controller cakephp-3.0
我是cakePHP 3的新手.我创建了一个控制器和模型,我调用一个函数来从数据库中获取所有用户.但是当我运行下面的代码时,我将得到以下错误"在布尔值上调用成员函数get_all_users()".
这个错误意味着什么,我该如何解决这个问题呢?
User.php(型号)
namespace App\Model\Entity;
use Cake\ORM\Entity;
class User extends Entity {
public function get_all_users() {
// find users and return to controller
return $this->User->find('all');
}
}
Run Code Online (Sandbox Code Playgroud)
UsersController.php(控制器)
namespace App\Controller;
use App\Controller\AppController;
class UsersController extends AppController {
public function index() {
// get all users from model
$this->set('users', $this->User->get_all_users());
}
}
Run Code Online (Sandbox Code Playgroud)
ndm*_*ndm 16
通常,当使用控制器的不存在的属性时会发生此错误.
与控制器名称匹配的表不需要手动加载/设置为属性,但即使它们最初也存在,尝试访问它们会导致调用控制器魔术getter方法,这将用于延迟加载表类它属于控制器,它会false在错误时返回,而这就是它发生的地方,你将在布尔值上调用一个方法.
https://github.com/cakephp/.../blob/3.0.10/src/Controller/Controller.php#L339
在您的情况下,问题是User(单数,对于实体)与预期不匹配Users(复数,对于表),因此不能找到匹配的表类.
您的自定义方法应该放在表类中,而不是UsersTable您应该通过该类访问的类
$this->Users
Run Code Online (Sandbox Code Playgroud)
您可能想要重新读取文档,实体不查询数据(除非您是实现延迟加载),它们代表数据集!