CakePHP 3:即使未从数据库中提取数据,也会返回true

时间:2016-07-14 07:52:26

标签: php cakephp cakephp-3.2

我在CakePHP 3.2工作。有一个表user_addresses我试图获取用户的所有记录

public function myFun()
{
    $this->loadModel('UserAddresses');
    $user_id = $this->Auth->user('id');
    $userAddresses = $this->UserAddresses->find('all', [
       'conditions' => [
           'user_id' => $user_id
       ]
    ]);
    if (empty($userAddresses)) {
       echo 'Hello';               // for testing only
    } else {
       echo 'World';
    }
}

要检查一下,我已将myFun添加到控制器的beforeFilter

$this->Auth->allow(['myFun']);

并打印世界而不是 Hello ,因为没有从数据库中检索到数据,因为如果用户未登录,则$user_id必须为空。< / p>

1 个答案:

答案 0 :(得分:1)

首先检查$user_id是否可用,然后调用find()方法。

public function myFun()
{
    $this->loadModel('UserAddresses');
    $user_id = $this->Auth->user('id');
    if(empty($user_id)){
        echo "Not able to access this method";
        die();
    }
    $userAddresses = $this->UserAddresses->find('all', [
       'conditions' => [
           'user_id' => $user_id
       ]
    ]);
    if (empty($userAddresses)) {
       echo 'Hello';               // for testing only
    } else {
       echo 'World';
    }
}