public function getRelatedUserQuery($model, $relations, $user = null, $baseConditions = [], $baseParams = [], $primaryKey = null)
    {
        if ($user === null) {
            $user = \Yii::$app->user->identity;
        }

        $query = new Query;

        if ($user === null) {
            return $query->andWhere('1=0');
        }

        if ($primaryKey === null) {
            $pkExpression = $this->quoteColumn('t', $model::primaryKey(), $model->getDb()->getSchema());
            if (count($model::primaryKey()) > 1) {
                $pkExpression = "ROW($pkExpression)";
            }
        } elseif (!is_array($primaryKey)) {
            $pkExpression = ':relationAuthorizer_pk';
            $query->params[':relationAuthorizer_pk'] = $primaryKey;
        } else {
            if (($key = key($primaryKey)) !== null && !is_numeric($key)) {
                // sort primaryKey by $model::primaryKey()
                $keys = array_flip($model::primaryKey());
                uksort(
                    $primaryKey,
                    function ($a, $b) use ($keys) {
                        return $keys[$a] - $keys[$b];
                    }
                );
            }
            $pkExpression = [];
            foreach (array_values($primaryKey) as $index => $pk) {
                $pkExpression[] = ':relationAuthorizer_pk'.$index;
                $query->params[':relationAuthorizer_pk'.$index] = $pk;
            }
            $pkExpression = 'ROW('.implode(',', $pkExpression).')';
        }

        /** @var ActiveQuery[] $relationQueries */
        $relationQueries = $this->getCompositeRelatedUserQuery($model, $relations, $user, $baseConditions, $baseParams);
        $conditions = ['OR'];
        foreach ($relationQueries as $relationQuery) {
            if (empty($relationQuery->where)
                || (!empty($baseConditions) && $relationQuery->where === $baseConditions)
            ) {
                continue;
            }
            $relationQuery->select($this->quoteColumn('t', $model::primaryKey(), $model->getDb()->getSchema()));
            $command = $relationQuery->createCommand($model->getDb());
            $conditions[] = $pkExpression.' IN ('.$command->getSql().')';
            $query->params = array_merge($query->params, $relationQuery->params);
        }
        if ($conditions !== ['OR']) {
            $query->where = $conditions;
        }
        return $query;
    }