CakePHP 3.7.7。这是我的用户表:
CREATE TABLE users (
id int(11) NOT NULL AUTO_INCREMENT,
user_level_id int(11) NOT NULL,
email varchar(255) NOT NULL,
password varchar(255) NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY email (email),
KEY user_level_id (user_level_id),
CONSTRAINT users_ibfk_1 FOREIGN KEY (user_level_id) REFERENCES user_levels (id) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
和用户级别:
CREATE TABLE user_levels (
id int(11) NOT NULL AUTO_INCREMENT,
level varchar(255) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
在我看来,我可以通过外键通过以下方式访问level
值:
<td><?= $user->has('user_level') ? $this->Html->link($user->user_level->level, ['controller' => 'UserLevels', 'action' => 'view', $user->user_level->id]) : '' ?></td>
我需要做同样的事情(在sidebar-menu.ctp, that as no controller associated) with the current logged user retrieved by
$ Auth-> user()`中。
在这种情况下,我不明白什么是正确的语法:
$Auth->user()['user_level']
导致:
未定义索引:user_level
但是:
$Auth->user()['user_level_id']
有效,即使这不是我想要的。
这是我在AppController.php中定义$Auth
的方式:
公共函数initialize() { parent :: initialize();
$this->loadComponent('RequestHandler', [
'enableBeforeRedirect' => false,
]);
$this->loadComponent('Flash', ['clear' => true]);
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
]
]
],
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
'unauthorizedRedirect' => $this->referer()
]);
}
public function beforeRender(Event $event)
{
$this->viewBuilder()->setTheme('AdminLTE');
$this->viewBuilder()->setClassName('AdminLTE.AdminLTE');
$this->set('Auth', $this->Auth);
}
public function isAuthorized($user = null)
{
return false;
}
以及在UsersController.php中:
public function initialize()
{
parent::initialize();
$this->Auth->allow(['login']);
}
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error(__('Username or password is incorrect.'));
}
}
答案 0 :(得分:1)
默认情况下,Auth组件仅从单个模型中获取数据,在这种情况下为用户。
如果要通过关系在Auth会话中存储数据,请在UsersTable中使用自定义查找器。
身份验证设置示例:
'authenticate' => [
'Form' => [
'finder' => 'emailOrNameAuth',
'fields' => ['username' => 'name', 'password' => 'password']
]
],
UsersTable:
public function findEmailOrNameAuth(\Cake\ORM\Query $query, array $options)
{
$query
->where(
[
'OR' => [
'email' => $options['username'],
'name' => $options['username']
],
'activated' => 1,
]
)
->contain(['UserLevels']); // <----
return $query;
}
阅读:
https://api.cakephp.org/3.7/class-Cake.Auth.FormAuthenticate.html
https://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#custom-find-methods
https://book.cakephp.org/3.0/en/controllers/components/authentication.html#customizing-find-query