【问题标题】:CakePHP 3 : returns true even if data is not fetched from databaseCakePHP 3:即使没有从数据库中获取数据,也返回 true
【发布时间】:2016-07-14 07:52:25
【问题描述】:

我正在使用 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']);

这会打印 World 而不是 Hello,因为没有从数据库中检索到数据,因为如果用户未登录,则 $user_id 必须为空。

【问题讨论】:

  • 您应该对调试更加熟悉。因此,您遇到的问题似乎不是您所期望的值,嗯,您应该做的第一件事就是调试该值,以便确定究竟是什么它实际上是(debug($userAddresses))!对于知道问题出在哪里的人来说可能很明显,但这些细节仍然应该在你的问题中,通常在收集这些信息时问题甚至会自行解决。

标签: php cakephp cakephp-3.2


【解决方案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';
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-21
    • 2018-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多