我在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>
答案 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';
}
}