0

我已经像这样设置了一个数据库表:

table: group
id     name          subGroupOf
1      grandparent   NULL
2      parent           1
3      child            2

这是我在 php 中尝试做的事情:

当用户访问一个页面时,该页面会告诉 auth() 函数他们需要“子”权限。因为“child”是“parent”的子组,所以两个组的成员都应该获得许可。但是,父母是“祖父母”的子组,因此所有三个组的成员都应该有权访问。

由于可以嵌套多少子组没有限制,我知道我需要一个循环。但我完全是空白。

我知道它需要检查组是否是 subGroupOf,如果是,则验证父组。这是我到目前为止所拥有的:

        // Get group of current user
        $group = mysqli_query($cxn,'SELECT group FROM user WHERE id='.$userID);

        // Compare group to permissions
        if($group == $permissions)
            return TRUE;

        // Check if group is a sub group
        $subGroupOf = mysqli_query($cxn,'SELECT subGroupOf FROM group WHERE id="'.$group.'"');
        if($subGroupOf == NULL)
        {
            // Wrong permissions
        }

        // Check if the parent group matches permissions
        if($subGroupOf == $permissions)
            return TRUE;

不知何故,我需要循环最后一部分,并在它到达时停止

$subGroupOf == NULL

我对编程很陌生,所以我仍在弄清楚逻辑......有什么想法吗?我不需要为我编写的全部内容(无论如何都总结了代码),我只需要帮助弄清楚结构..

4

2 回答 2

0

另一种方法,但您仍然需要一个递归函数:

  1. 创建一个将组的层次结构添加到数组的函数
  2. 遍历组数组,并检查您的权限。

功能

function getGroupHierarchy($groupId, $cxn)
{
    $groupArray = array();

    //Push the group to the array..
    $groupArray[] = $groupId;

    //Get the parent id of this group
    $subGroupOf = mysqli_query($cxn,'SELECT subGroupOf FROM group WHERE id="'.$groupId.'"');

    //There is no parent, just return the array.
    if($subGroupOf == NULL)
    {
        return $groupArray;
    }

    //Continue checking the parent group(s).
    getGroupHierarchy($subGroupOf, $cxn);
}

调用该函数并检查权限:

// Get group of current user
$groupId = mysqli_query($cxn,'SELECT group FROM user WHERE id='.$userID);

$allGroups = getGroupHierarchy($groupId, $cxn);

//Compare each group to permissions.
foreach($groupArray as $group)
{
    if($group == $permissions)
        return TRUE;
}
于 2012-09-12T19:42:52.563 回答
0

您可以通过检查子组的递归函数来执行此操作,并一直持续到“subGroupOf”id 为 NULL。

例如:

function getTopParentGroup($groupId, $cxn) {
    $subGroupOf = mysqli_query($cxn,'SELECT subGroupOf FROM group WHERE id="'.$groupId.'"');

    //There is no parent, just return the group
    if($subGroupOf == NULL)
    {
        return $group;
    }
    //A parent has been found, continue...  
    getTopParentGroup($subGroupOf, $cxn);
}
于 2012-09-12T19:16:57.257 回答