Scope to select users having a specific
role. Role can be an id or slug.

@param \Illuminate\Database\Eloquent\Builder $query
@param int|string $role
@param string $column
@return \Illuminate\Database\Eloquent\Builder
193318
public function scopeRole($query, $role, $column = null)
    {
        if (is_null($role)) {
            return $query;
        }

        return $query->whereHas('roles', function ($query) use ($role, $column) {
            if (is_array($role)) {
                $queryColumn = !is_null($column) ? $column : 'roles.slug';

                $query->whereIn($queryColumn, $role);
            } else {
                $queryColumn = !is_null($column) ? $column : (is_numeric($role) ? 'roles.id' : 'roles.slug');

                $query->where($queryColumn, $role);
            }
        });
    }
400431
public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*'])
    {
        if ($query->getQuery()->from == $parentQuery->getQuery()->from) {
            return $this->getRelationExistenceQueryForSelfRelation($query, $parentQuery, $columns);
        }

        return parent::getRelationExistenceQuery($query, $parentQuery, $columns);
    }
786439
public function scopeWhereRoleIs($query, $role = '', $team = null, $boolean = 'and')
    {
        $method = $boolean == 'and' ? 'whereHas' : 'orWhereHas';

        return $query->$method('roles', function ($roleQuery) use ($role, $team) {
            $teamsStrictCheck = Config::get('laratrust.teams_strict_check');
            $roleQuery->where('name', $role)
                ->when($team || $teamsStrictCheck, function ($query) use ($team) {
                    $team = Helper::getIdFor($team, 'team');
                    return $query->where(Helper::teamForeignKey(), $team);
                });
        });
    }
1325646
public function getRelationExistenceQueryForSelfJoin(Builder $query, Builder $parentQuery, $columns = ['*'])
    {
        $query->select($columns);

        $query->from($this->related->getTable().' as '.$hash = $this->getRelationCountHash());

        $this->related->setTable($hash);

        $this->performJoin($query);

        return parent::getRelationExistenceQuery($query, $parentQuery, $columns);
    }
175082
public function scopeWherePermissionIs($query, $permission = '', $boolean = 'and')
    {
        $method = $boolean == 'and' ? 'where' : 'orWhere';

        return $query->$method(function ($query) use ($permission) {
            $query->whereHas('roles.permissions', function ($permissionQuery) use ($permission) {
                $permissionQuery->where('name', $permission);
            })->orWhereHas('permissions', function ($permissionQuery) use ($permission) {
                $permissionQuery->where('name', $permission);
            });
        });
    }
523167
public function getRelationQuery(Builder $query, Builder $parent, $columns = ['*'])
	{
		if ($parent->getQuery()->from == $query->getQuery()->from) {
			return $this->getRelationQueryForSelfJoin($query, $parent, $columns);
		}

		$this->setJoin($query);

		return parent::getRelationQuery($query, $parent, $columns);
	}
846557
public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*'])
    {
        if ($parentQuery->getQuery()->from == $query->getQuery()->from) {
            return $this->getRelationExistenceQueryForSelfRelation($query, $parentQuery, $columns);
        }

        return $query->select($columns)->whereColumn(
            $this->getQualifiedForeignKeyName(), '=', $query->qualifyColumn($this->ownerKey)
        );
    }
1023285
public function getRelationExistenceQueryForSelfRelation(Builder $query, Builder $parentQuery, $columns = ['*'])
    {
        $query->from($query->getModel()->getTable().' as '.$hash = $this->getRelationCountHash());

        $query->getModel()->setTable($hash);

        return $query->select($columns)->whereColumn(
            $this->getQualifiedParentKeyName(), '=', $hash.'.'.$this->getForeignKeyName()
        );
    }
36094
public function	beforeFind(Event $event, Query $query, ArrayObject $options, $primary) 
    {
        if ($primary === false) {
            return $query;
        }
        
        if ($this->hasField('user_id') && \Rita::$user['role_id'] !== 1) {
            $query->where(['user_id' => \Rita::$user['id']]);    
        }    
        
        return $query;
    }
843861
public function findUsersByRolesIncludingGroups(
        array $roles,
        $executeQuery = true
    )
    {
        $dql = "
            SELECT u, r1, g, r2, ws
            From Claroline\CoreBundle\Entity\User u
            LEFT JOIN u.roles r1
            LEFT JOIN u.personalWorkspace ws
            LEFT JOIN u.groups g
            LEFT JOIN g.roles r2
            WHERE (r1 in (:roles)
            OR r2 in (:roles))
            AND u.isEnabled = true
            ORDER BY u.lastName, u.firstName ASC";

        $query = $this->_em->createQuery($dql);
        $query->setParameter('roles', $roles);

        return ($executeQuery) ? $query->getResult() : $query;
    }
963318
public function getRelationQueryForSelfJoin(Builder $query, Builder $parent, $columns = ['*'])
	{
		$query->select($columns);

		$query->from($this->related->getTable().' as '.$hash = $this->getRelationCountHash());

		$this->related->setTable($hash);

		$this->setJoin($query);

		return parent::getRelationQuery($query, $parent, $columns);
	}
1261239
public function scopeArea(Builder $query, $areas)
    {
        $query->with('roles')->whereNotNull('tbl_users.id');
        if (empty($areas)) {
            return $query;
        }
        $query->whereHas('roles', function ($query) use ($areas) {
            $query->whereIn('tbl_roles.area', (array) $areas);
        });

        return $query;
    }
1318357
public function index($role = null) {
		$this->loadModel(CLASS_USERS);

		$query = $this->Users->find()
			->where([$this->Users->getDisplayField() . ' IS NOT' => null]);
		if ($this->param('search')) {
			$query = $query->where([$this->Users->getDisplayField() . ' LIKE' => '%' . $this->param('search') . '%']);
		}

		if ($role && $this->Users->getSchema()->getColumn('role_id')) {
			$query = $query->where(['role_id' => (int)$role]);
		}

		/** @var \App\Model\Entity\User[] $users */
		$users = $query->orderDesc($this->Users->getPrimaryKey())->limit(100)->all()->toArray();

		$count = count($users);
		if ($count < 1) {
			$this->err($count . ' users found');
		} else {
			$this->success($count . ' users found');
		}

		$displayField = $this->Users->getDisplayField();
		$emailField = null;
		if ($this->Users->getSchema()->getColumn('email') && $displayField !== 'email') {
			$emailField = 'email';
		}

		foreach ($users as $user) {
			$this->out('* ' . $user->get($displayField) . ($emailField ? ' (' . $user->get($emailField) . ')' : ''));
			if ($this->param('verbose')) {
				$this->out($user);
			}
		}
		if ($count > 200) {
			$this->warn('(Only lists 200 users)');
		}
	}
660295
protected function setPodiumUserRole($user, $role)
    {
        $rbac = Podium::getInstance()->getRbac();
        $userRoles = $rbac->getRolesByUser($user->id);
        $podiumRoles = array_filter($userRoles, function ($role) {
            return strpos($role->name, 'podium') === 0;
        });
        foreach ($podiumRoles as $podiumRole) {
            $rbac->revoke($podiumRole, $user->id);
        }
        $rbac->assign($role, $user->id);
    }
1121908
public function giveUserRole($user, $role)
    {
        $user   =   $this->findUserById($user);
        $role   =   $this->findRoleByKey($role);

        if ($user->is($role->key)) {
            return true;
        }
        
        return $user->join($role);
    }
1050238
public function select($query)
    {
        $clause = 'SELECT @DISTINCT';

        if ($query->operation['type'] & AnDomainQuery::QUERY_SELECT_DEFAULT) {
            $description = $query->getRepository()->getDescription();
            $columns = AnDomainQueryHelper::parseColumns($query, $query->columns);
            foreach ($description->getProperty() as $name => $property) {
                if (isset($columns[$name])) {
                    $result = AnDomainQueryHelper::parseColumn($query, $name);
                    if ($result['columns'] instanceof AnDomainResourceColumn) {
                        $columns[] = $columns[$name].' AS '.$this->_store->quoteValue($result['columns']->key());
                        unset($columns[$name]);
                    }
                } elseif ($property->isAttribute()) {
                    $columns[] = $property->getColumn();
                } elseif ($property->isRelationship() && $property->isManyToOne()) {
                    $columns = array_merge($columns, array_values(AnConfig::unbox($property->getColumns())));
                }
            }

            if ($description->getInheritanceColumn()) {
                $columns[] = $description->getInheritanceColumn();
            }

            foreach ($columns as $key => $column) {
                if ($column instanceof AnDomainResourceColumn) {
                    if ($column->resource->getLink()) {
                        $columns[$key] = $column.' AS '.$this->_store->quoteValue((string) $column);
                        continue;
                    } else {
                        $columns[$key] = (string) $column;
                    }
                }
                if (!is_numeric($key)) {
                    $columns[$key] = $column.' AS '.$this->_store->quoteValue($key);
                }
            }
            $clause .= ' '.implode(' , ', $columns);
        } else {
            $columns = (array) $query->operation['value'];
            $columns = AnDomainQueryHelper::parseColumns($query, $columns);
            $clause .= ' '.implode(' , ', $columns);
        }

        return $clause;
    }
509009
public function getRelationQuery(Builder $query, Builder $parent, $columns = ['*'])
    {
        $table = $this->getParent()->getTable();
        $query = parent::getRelationQuery($query, $parent, $columns);

        return $query->where("{$table}.{$this->morphType}", '=', $this->morphName);
    }