有没有一种方法可以优化用户映射?

时间:2019-10-31 06:25:43

标签: sql laravel optimization eloquent

我已经创建了一个调用此getUserIdsByAllBranches()的方法,返回值将是一个数组。如果array不为空,我将进行另一个处理。但是我在映射或获取具有所有分支的所有用户时遇到了问题。

代码如下:

/**
 * Get all User Ids of Branch Permission User
 * By All Branches
 * @param Array
 * @return Array
 */
public function getUserIdsByAllBranches($override = [])
{
    if (count($override) !== 0) {
        foreach($override as $property => $value) {
            ${$property} = $value;
        }
    } else {
        $branchLength = App::make(BranchRepository::class)->get()->count();
    }

    $userIdsWithAllBranches = [];
    $userIds = $this->getUserIds();

    foreach($userIds as $userId) {
        $identical = true;

        $userBranchIds = array_values($this->get()
            ->where('user_id', $userId)
            ->pluck(['branch_id'])
            ->unique()
            ->toArray());

        if(count($userBranchIds) === $branchLength) {
            $initialPermissions = []; 

            foreach($userBranchIds as $index => $userBranchId) {
                if(!$identical) {
                    continue;
                }

                $branchUserPermissions = $this->get()
                    ->where('user_id', $userId)
                    ->where('branch_id', $userBranchId)
                    ->sortBy('permission_id')
                    ->pluck(['permission_id']);

                if($index === 0) {
                    $initialPermissions = $branchUserPermissions;
                } else {
                    if($initialPermissions != $branchUserPermissions) {
                        $identical = false;
                    }
                }
            }
        } else {
            $identical = false;
        }
        if($identical) {
            array_push($userIdsWithAllBranches, $userId);
        }
    }
    return $userIdsWithAllBranches;
}

/**
 * Get all User Ids of Branch Permission User
 *
 * @return Array
 */
public function getUserIds()
{
    return array_values($this->get()
            ->sortBy('user_id')
            ->pluck(['user_id'])
            ->unique()
            ->toArray());
}

此方法getUserIds()将返回分支权限用户表的所有用户ID。

分支权限用户表:

  • branch_id
  • permission_id
  • user_id

0 个答案:

没有答案