dsvf46980
2016-07-14 07:52
浏览 47
已采纳

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

I'm working in CakePHP 3.2. There is a table user_addresses from which I'm trying to fetch all records of an user

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';
    }
}

To check it, I added myFun to controller's beforeFilter

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

and this prints World instead of Hello since there is no data retrieved from database because if user is not logged in then $user_id must be empty.

图片转代码服务由CSDN问答提供 功能建议

我在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';  //仅用于测试
} else {
 echo'World'; 
} 
} 
   
 
 

要检查它,我添加了 myFun 到控制器的 beforeFilter

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

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

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doutang3760 2016-07-14 12:15
    已采纳

    First of all check if $user_id is available then and then call find() method.

    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';
        }
    }
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题