How to retrieve information when linking models through a table in CakePHP 3.0?

I'm trying to set up a user access model based on the one in the CakePHP blog tutorial (http://book.cakephp.org/3.0/en/tutorials-and-examples/blog-auth-example/auth.html), but with Roles in a separate table, and linked to users by a UserRoles table.

I currently have the following in Model/Table/UsersTable.php:

    $this->belongsToMany('Roles', [
        'through' => 'UserRoles'
    ]);

and the following in Model/Table/RolesTable.php:

    $this->belongsToMany('Users', [
        'through' => 'UserRoles'
    ]);

and the following in Model/Table/UserRolesTable.php:

    $this->belongsTo('Users', [
        'foreignKey' => 'user_id'
    ]);
    $this->belongsTo('Roles', [
        'foreignKey' => 'role_id'
    ]);

I have view, create, and administrator roles created. I'm trying to figure out how to check a user's role or roles in AppController.php. This is the simple example given for when the role incorporated into the user object:

public function isAuthorized($user)
{
    // Admin can access every action
    if (isset($user['role']) && $user['role'] === 'admin') {
        return true;
    }

    // Default deny
    return false;
}

I'm not sure how to access the User object and get the user's role by the user's ID from the AppController file. Since the user is not linked to the role directly, how would I access the role information from an IsAuthorized function? How would I do a lookup to retrieve the user's role when it is linked by another table? Thank you!


在控制器中设置AuthComponent时,请确保告诉它提取相关数据:

public function initialize()
{
    parent::initialize();
    $this->loadComponent('Auth', [
        'authenticate' => [
            'Form' => [
                'contain' => ['Roles']
            ]
        ]
    ]);
}
链接地址: http://www.djcxy.com/p/58830.html

上一篇: CakePHP 3:存在的路由缺少路由错误

下一篇: 如何在通过CakePHP 3.0中的表链接模型时检索信息?