/** * @param Entity $entity * @param Select $query * @param array $with * @param string $prefix * * @return Select */ private function joinRelationsToQuery(Entity $entity, Select $query, array $with, $prefix = '') { if ($prefix === '') { $leftAlias = $this->alias ?: $entity->getTable(); } else { $leftAlias = $prefix; $prefix .= '_'; } foreach (array_filter($with, [$entity, 'hasRelation']) as $relationName) { $relation = $entity->getRelation($relationName); $relatedEntity = $relation->getEntity(); $alias = $prefix . $relationName; $query->addSelect(array_map(function ($item) use($alias) { return "{$alias}.{$item} as {$alias}_{$item}"; }, array_values($relatedEntity->getFieldNames()))); $relation->joinToQuery($query, $leftAlias, $alias); $strippedWith = Utils::filterPrefixedElements($with, $relationName . '.', Utils::FILTER_REMOVE_PREFIX); $this->joinRelationsToQuery($relatedEntity, $query, $strippedWith, $alias); } return $query; }