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

假如想象 提交于 2019-12-23 04:24:23

问题


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!


回答1:


When setting up the AuthComponent in your controller, make sure you tell it to fetch related data:

public function initialize()
{
    parent::initialize();
    $this->loadComponent('Auth', [
        'authenticate' => [
            'Form' => [
                'contain' => ['Roles']
            ]
        ]
    ]);
}


来源:https://stackoverflow.com/questions/29405078/how-to-retrieve-information-when-linking-models-through-a-table-in-cakephp-3-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!