CakePHP $this->Auth->user("id")总是返回null


CakePHP $this->Auth->user("id") always return null?

我有一个函数,我使用它来获取Auth组件的用户id。它工作良好,不使用return json_encode。问题是,我需要这与json_encode工作,因为我从ajax请求获取值。使用json_encode,它总是返回null到id,我不明白为什么会发生这种情况。问题是下面的函数indexAjax()

我怎么能使用$this->Auth->user("id")json_encode,它不返回null ?

尝试。

//using $this->set it works fine
public function index() {       
                $id = $this->Auth->user("id");                
                $empresas = $this->Empresa->find('all', array(
                            'fields'=>array("id", "nomeFantasia", "cnpj",
                                    "telefone1", "telefone2", "celular", "aberto"),
                            'conditions'=>array("users_id = "=> $id)            
                           ));             
                debug($id) or die;
                //$this->set(compact('empresas'));
    }

//with json_encode always return null
 public function indexAjax() {      
                $this->autoRender = false;
                $id = $this->Auth->user("id");
                $empresas = $this->Empresa->find('all', array(
                            'fields'=>array("id", "nomeFantasia", "cnpj",
                                    "telefone1", "telefone2", "celular", "aberto"),
                            'conditions'=>array("users_id = "=> $id)            
                           ));
                return json_encode($id);                
    }

解决了这个问题。我的解决方案是当用户登录时,我获得用户id并写入会话,所以当我需要这个id时,我直接从会话中获取,而不是从AuthComponent中获取。