問題描述
我是 cakePHP 3 的新手.我創(chuàng)建了一個控制器和模型,我在其中調(diào)用了一個函數(shù)來從數(shù)據(jù)庫中獲取所有用戶.但是當(dāng)我運行下面的代碼時,我會得到以下錯誤在布爾值上調(diào)用成員函數(shù) 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());
}
}
推薦答案
通常在使用控制器的不存在的屬性時會發(fā)生此錯誤.
Generally this error happens when a non-existent property of a controller is being used.
與控制器名稱匹配的表不需要是手動加載/設(shè)置為屬性,但即使它們最初不存在,嘗試訪問它們會導(dǎo)致調(diào)用控制器魔術(shù)getter方法,該方法用于延遲加載表類屬于控制器,它在出錯時返回 false
,這就是它發(fā)生的地方,你將調(diào)用一個布爾值的方法.
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
(單數(shù),對于實體)與預(yù)期的 Users
(復(fù)數(shù),對于表)不匹配,因此沒有匹配的表類可以找到.
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.
你的自定義方法應(yīng)該放在一個表類中,UsersTable
類,然后你應(yīng)該通過
Your custom method should go in a table class instead, the UsersTable
class, which you should then access via
$this->Users
您可能想重新閱讀文檔,實體不查詢數(shù)據(jù)(除非您例如實施延遲加載),它們代表一個數(shù)據(jù)集!
You may want to reread the docs, entities do not query data (unless you are for example implementing lazy loading), they represent a dataset!
這篇關(guān)于調(diào)用布爾成員函數(shù)是什么意思以及如何修復(fù)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!