問題描述
我是 cakePHP 3 的新手.我創建了一個控制器和模型,我在其中調用了一個函數來從數據庫中獲取所有用戶.但是當我運行下面的代碼時,我會得到以下錯誤在布爾值上調用成員函數 get_all_users()".
I'm new with cakePHP 3. I have created a controller and model where I call a function to get all users from the database. But when I run the code below I will get the following error "Call to a member function get_all_users() on boolean".
這個錯誤是什么意思,我該如何解決?
what does this error means and how can I fix this up?
User.php(模型)
namespace AppModelEntity;
use CakeORMEntity;
class User extends Entity {
public function get_all_users() {
// find users and return to controller
return $this->User->find('all');
}
}
UsersController.php(控制器)
namespace AppController;
use AppControllerAppController;
class UsersController extends AppController {
public function index() {
// get all users from model
$this->set('users', $this->User->get_all_users());
}
}
推薦答案
通常在使用控制器的不存在的屬性時會發生此錯誤.
Generally this error happens when a non-existent property of a controller is being used.
與控制器名稱匹配的表不需要是手動加載/設置為屬性,但即使它們最初不存在,嘗試訪問它們會導致調用控制器魔術getter方法,該方法用于延遲加載表類屬于控制器,它在出錯時返回 false
,這就是它發生的地方,你將調用一個布爾值的方法.
Tables that do match the controller name do not need to be loaded/set to a property manually, but not even they exist initially, trying to access them causes the controllers magic getter method to be invoked, wich is used for lazy loading the table class that belongs to the controller, and it returns false
on error, and that's where it happens, you will be calling a method on a boolean.
https://github.com/cakephp/.../blob/3.0.10/src/Controller/Controller.php#L339
在您的情況下,問題是 User
(單數,對于實體)與預期的 Users
(復數,對于表)不匹配,因此沒有匹配的表類可以找到.
In your case the problem is that User
(singular, for entities) doesn't match the expected Users
(plural, for tables), hence no matching table class can be found.
你的自定義方法應該放在一個表類中,UsersTable
類,然后你應該通過
Your custom method should go in a table class instead, the UsersTable
class, which you should then access via
$this->Users
您可能想重新閱讀文檔,實體不查詢數據(除非您例如實施延遲加載),它們代表一個數據集!
You may want to reread the docs, entities do not query data (unless you are for example implementing lazy loading), they represent a dataset!
這篇關于調用布爾成員函數是什么意思以及如何修復的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!