在CakePHP 3.0中通过表格连接模型时如何检索信息? [英] How to retrieve information when linking models through a table in CakePHP 3.0?

查看:168
本文介绍了在CakePHP 3.0中通过表格连接模型时如何检索信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试根据CakePHP博客教程中的用户访问模型设置用户访问模型( http://book.cakephp.org/3.0/en/tutorials-and-examples/blog-auth-example/auth.html ),但在一个单独的表中的角色,并通过UserRoles表链接到用户。

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.

我目前在Model / Table / UsersTable.php中有以下:

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

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

以及Model / Table / RolesTable.php中的以下内容:

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

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

以及Model / Table / UserRolesTable.php中的以下内容:

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

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

我创建了视图,创建和管理员角色。我试图找出如何检查用户的角色或角色在AppController.php。这是为角色合并到用户对象时给出的简单示例:

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;
}


$ b $ p

我不知道如何访问User对象并获得用户角色通过AppController文件中的用户ID。由于用户没有直接链接到角色,我将如何从IsAuthorized函数访问角色信息?当用户的角色由另一个表链接时,我如何执行查找来检索用户的角色?
谢谢!

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时,请确保您告诉它获取相关数据:

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']
            ]
        ]
    ]);
}

这篇关于在CakePHP 3.0中通过表格连接模型时如何检索信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆