/** * método que adiciona a clausula where * @param query * @return query */ public function addWhere(\Doctrine\ORM\QueryBuilder &$query, \Core_Dto_Search $search, $nuCpfCnpjPassaporte) { $sqPessoa = $search->getSqPessoaCorporativo() ?: $search->getSqPessoa(); if ($sqPessoa) { $query->andWhere('p.sqPessoa = :sqPessoa')->setParameter('sqPessoa', $sqPessoa); } switch ($search->getSqTipoPessoa()) { case \Core_Configuration::getSgdoceTipoPessoaPessoaFisica(): $passaporte = $this->getDocumento(); $query->leftJoin('p.sqPessoaFisica', 'pf'); //passar cpf ou passaporte , passa parametro if ($nuCpfCnpjPassaporte != '') { if ($search->getSqNacionalidade() == '1') { $query->andWhere('pf.nuCpf = :nuCpf')->setParameter('nuCpf', $nuCpfCnpjPassaporte); } else { $query->leftJoin("p.sqPessoaDocumento", "d", "WITH", "d.sqAtributoTipoDocumento = :sqAtributoTipoDocumento")->setParameter("sqAtributoTipoDocumento", $passaporte['sqAtributoTipoDocumento'])->andWhere('pf.sqNacionalidade <> :sqNacionalidade')->setParameter('sqNacionalidade', '1')->andWhere('d.txValor = :txValor')->setParameter('txValor', $nuCpfCnpjPassaporte); } } break; case \Core_Configuration::getSgdoceTipoPessoaPessoaJuridica(): $query->leftJoin('p.sqPessoaJuridica', 'pj'); if ($nuCpfCnpjPassaporte != '') { $query->andWhere('pj.nuCnpj = :nuCnpj')->setParameter('nuCnpj', $nuCpfCnpjPassaporte); } break; case \Core_Configuration::getSgdoceTipoPessoaMinisterioPublico(): $query->leftJoin('p.sqUnidadeOrgInterna', 'ui'); $query->leftJoin('p.sqRppn', 'rpn'); break; case \Core_Configuration::getSgdoceTipoPessoaOutrosOrgaos(): $query->leftJoin('p.sqUnidadeOrgExterna', 'ue'); break; } }
public function alterQueryBuilder(QueryBuilder $queryBuilder) { if ($this->year !== null) { $queryBuilder->andWhere('YEAR(transaction.date) = :year'); $queryBuilder->setParameter(':year', $this->year); } if ($this->month && in_array($this->month, array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))) { $queryBuilder->andWhere('MONTH(transaction.date) = :month'); $queryBuilder->setParameter(':month', $this->month); } if ($this->processed != null && in_array($this->processed, array(0, 1))) { $queryBuilder->andWhere('transaction.is_processed = :processed'); $queryBuilder->setParameter(':processed', $this->processed ? true : false); } if ($this->tag != null) { $queryBuilder->leftJoin('transaction.tags', 'tag'); $queryBuilder->andWhere('tag.slug = :tag'); $queryBuilder->setParameter(':tag', $this->tag); } if ($this->category !== null) { if ($this->category == 'empty') { $queryBuilder->andWhere('transaction.category IS NULL'); } else { $queryBuilder->leftJoin('transaction.category', 'category'); $queryBuilder->leftJoin('category.parent', 'parent'); $queryBuilder->andWhere('category.slug = :category or parent.slug = :category'); $queryBuilder->setParameter(':category', $this->category); } } return $queryBuilder; }
private function applyJoins(QueryBuilderFilter $filter, QueryBuilder $queryBuilder) { /** @var Join[] $previousJoins */ $previousJoins = array(); foreach ($filter->getJoins() as $join) { $joinEntity = $join->getEntityClassName(); $joinAlias = $join->getAlias(); if (!array_key_exists($joinEntity, $previousJoins)) { $previousJoins[$joinEntity] = $join; switch (get_class($join)) { case LeftJoinWith::class: /** @var LeftJoinWith $join */ $queryBuilder->leftJoin($joinEntity, $joinAlias, \Doctrine\ORM\Query\Expr\Join::WITH, $join->getWithCondition()); break; case LeftJoin::class: $queryBuilder->leftJoin($joinEntity, $joinAlias); break; case JoinWith::class: /** @var JoinWith $join */ $queryBuilder->join($joinEntity, $joinAlias, \Doctrine\ORM\Query\Expr\Join::WITH, $join->getWithCondition()); break; case Join::class: $queryBuilder->join($joinEntity, $joinAlias); break; default: throw new Exception('Invalid JOIN type: ' . get_class($join)); } } else { if ($previousJoins[$joinEntity]->getAlias() !== $joinAlias) { throw new InconsistentJoinsException($joinEntity, $previousJoins[$joinEntity]->getAlias(), $joinAlias); } } } }
/** * {@inheritdoc} */ protected function addJoinStatement($joinType, $join, $joinAlias, $joinConditionType, $joinCondition) { if ('left' === $joinType) { $this->qb->leftJoin($join, $joinAlias, $joinConditionType, $joinCondition); } else { $this->qb->innerJoin($join, $joinAlias, $joinConditionType, $joinCondition); } }
/** * Add completeness joins to query builder * * @param string $completenessAlias the join alias * @param string $locale the locale * @param sting $scope the scope * * @return CompletenessJoin */ public function addJoins($completenessAlias, $locale, $scope) { $rootAlias = $this->qb->getRootAlias(); $localeAlias = $completenessAlias . 'Locale'; $channelAlias = $completenessAlias . 'Channel'; $rootEntity = current($this->qb->getRootEntities()); $completenessMapping = $this->qb->getEntityManager()->getClassMetadata($rootEntity)->getAssociationMapping('completenesses'); $completenessClass = $completenessMapping['targetEntity']; $this->qb->leftJoin('PimCatalogBundle:Locale', $localeAlias, 'WITH', $localeAlias . '.code = :cLocaleCode')->leftJoin('PimCatalogBundle:Channel', $channelAlias, 'WITH', $channelAlias . '.code = :cScopeCode')->leftJoin($completenessClass, $completenessAlias, 'WITH', $completenessAlias . '.locale = ' . $localeAlias . '.id AND ' . $completenessAlias . '.channel = ' . $channelAlias . '.id AND ' . $completenessAlias . '.product = ' . $rootAlias . '.id')->setParameter('cLocaleCode', $locale)->setParameter('cScopeCode', $scope); return $this; }
/** * {@inheritdoc} */ public function addFieldSorter($field, $direction) { $rootAlias = $this->qb->getRootAlias(); $prefix = 'sorter'; $field = $prefix . 'familyLabel'; $family = $prefix . 'family'; $trans = $prefix . 'familyTranslations'; $this->qb->leftJoin($rootAlias . '.family', $family)->leftJoin($family . '.translations', $trans, 'WITH', $trans . '.locale = :dataLocale'); $this->qb->addSelect('COALESCE(' . $trans . '.label, CONCAT(\'[\', ' . $family . '.code, \']\')) as ' . $field); $this->qb->addOrderBy($field, $direction); return $this; }
/** ************************************************************************ * Filter the result which are after startDate and/or before endDate * @param QueryBuilder $qb * @param array $parameters **************************************************************************/ protected function filterByAccount(QueryBuilder $qb, array $parameters) { if (isset($parameters['account'])) { if ($parameters['account'] == NULL) { $qb->leftJoin('FinanceOperationBundle:Operation', 'o', 'WITH', $qb->expr()->eq('ao.id', 'o.id')); $qb->leftJoin('FinanceOperationBundle:TransferBetweenAccount', 'it', 'WITH', $qb->expr()->eq('ao.id', 'it.id')); $qb->leftJoin('FinanceOperationBundle:TransferBetweenAccount', 'ot', 'WITH', $qb->expr()->eq('ao.id', 'ot.id')); } else { $qb->leftJoin('FinanceOperationBundle:Operation', 'o', 'WITH', $qb->expr()->andX($qb->expr()->eq('ao.id', 'o.id'), $qb->expr()->eq('o.account', ':account')))->setParameter('account', $parameters['account'])->leftJoin('FinanceOperationBundle:TransferBetweenAccount', 'it', 'WITH', $qb->expr()->andX($qb->expr()->eq('ao.id', 'it.id'), $qb->expr()->eq('it.destinationAccount', ':account')))->setParameter('account', $parameters['account'])->leftJoin('FinanceOperationBundle:TransferBetweenAccount', 'ot', 'WITH', $qb->expr()->andX($qb->expr()->eq('ao.id', 'ot.id'), $qb->expr()->eq('ot.sourceAccount', ':account')))->setParameter('account', $parameters['account']); } } }
/** * {@inheritdoc} */ public function addAttributeFilter(AbstractAttribute $attribute, $operator, $value) { $joinAlias = 'filter' . $attribute->getCode() . $this->aliasCounter++; $backendField = sprintf('%s.%s', $joinAlias, $attribute->getBackendType()); if ($operator === 'EMPTY') { $this->qb->leftJoin($this->qb->getRootAlias() . '.values', $joinAlias, 'WITH', $this->prepareAttributeJoinCondition($attribute, $joinAlias)); $this->qb->andWhere($this->prepareCriteriaCondition($backendField, $operator, $value)); } else { $condition = $this->prepareAttributeJoinCondition($attribute, $joinAlias); $condition .= ' AND ' . $this->prepareCriteriaCondition($backendField, $operator, $value); $this->qb->innerJoin($this->qb->getRootAlias() . '.values', $joinAlias, 'WITH', $condition); } return $this; }
/** * Adds joins and conditions to the QueryBuilder in order to only return entities the given user is allowed to see. * * @param QueryBuilder $queryBuilder The instance of the QueryBuilder to adjust * @param UserInterface $user The user for which the access control is checked * @param int $permission The permission mask for which is checked * @param string $entityClass The class of the entity of which the access control is checked * @param string $entityAlias The alias of the entity used in the query builder */ protected function addAccessControl(QueryBuilder $queryBuilder, UserInterface $user, $permission, $entityClass, $entityAlias) { $queryBuilder->leftJoin(AccessControl::class, 'accessControl', 'WITH', 'accessControl.entityClass = :entityClass AND accessControl.entityId = ' . $entityAlias . '.id'); $queryBuilder->leftJoin('accessControl.role', 'role'); $queryBuilder->andWhere('BIT_AND(accessControl.permissions, :permission) = :permission OR accessControl.permissions IS NULL'); $roleIds = []; foreach ($user->getRoleObjects() as $role) { $roleIds[] = $role->getId(); } $queryBuilder->andWhere('role.id IN(:roleIds) OR role.id IS NULL'); $queryBuilder->setParameter('roleIds', $roleIds); $queryBuilder->setParameter('entityClass', $entityClass); $queryBuilder->setParameter('permission', $permission); }
/** * {@inheritdoc} */ public function addAttributeSorter(AttributeInterface $attribute, $direction, $locale = null, $scope = null) { $aliasPrefix = 'sorter'; $joinAlias = $aliasPrefix . 'V' . $attribute->getCode(); $backendType = $attribute->getBackendType(); // join to value $condition = $this->prepareAttributeJoinCondition($attribute, $joinAlias, $locale, $scope); $this->qb->leftJoin($this->qb->getRootAlias() . '.values', $joinAlias, 'WITH', $condition); $joinAliasMetric = $aliasPrefix . 'M' . $attribute->getCode(); $this->qb->leftJoin($joinAlias . '.' . $backendType, $joinAliasMetric); $this->qb->addOrderBy($joinAliasMetric . '.baseData', $direction); $idField = $this->qb->getRootAlias() . '.id'; $this->qb->addOrderBy($idField); return $this; }
/** * {@inheritdoc} */ public function entityJoin(array $associationMappings) { $alias = $this->queryBuilder->getRootAlias(); $newAlias = 's'; $joinedEntities = $this->queryBuilder->getDQLPart('join'); foreach ($associationMappings as $associationMapping) { // Do not add left join to already joined entities with custom query foreach ($joinedEntities as $joinExprList) { foreach ($joinExprList as $joinExpr) { $newAliasTmp = $joinExpr->getAlias(); if (sprintf('%s.%s', $alias, $associationMapping['fieldName']) === $joinExpr->getJoin()) { $this->entityJoinAliases[] = $newAliasTmp; $alias = $newAliasTmp; continue 3; } } } $newAlias .= '_' . $associationMapping['fieldName']; if (!in_array($newAlias, $this->entityJoinAliases)) { $this->entityJoinAliases[] = $newAlias; $this->queryBuilder->leftJoin(sprintf('%s.%s', $alias, $associationMapping['fieldName']), $newAlias); } $alias = $newAlias; } return $alias; }
/** * Applies a custom query to the QueryBuilder * * @param QueryBuilder $qb The query builder * @param ManagerFilter $filter The query filter */ protected function applyCustomQuery(QueryBuilder $qb, ManagerFilter $filter) { // Apply special handling for non-direct fields in relations, where the frontend has no idea about. foreach ($filter->getSorters() as $sorter) { switch ($sorter->getSortField()) { case "q.part_name": $qb->join("q.part", "p"); $sorter->setSortField("p.name"); break; case "q.user_id": $qb->leftJoin("q.user", "u"); $sorter->setSortField("u.username"); break; case "q.direction": $sorter->setSortField("q.dateTime"); break; case "q.storageLocation_name": $qb->join("q.part", "p")->join("p.storageLocation", "st"); $sorter->setSortField("st.name"); break; default: break; } } }
/** * (non-PHPdoc) * @see \PartKeepr\Manager\AbstractManager::applyCustomQuery() */ protected function applyCustomQuery(QueryBuilder $qb, ManagerFilter $filter) { /** * Pull in additional tables */ $qb->leftJoin("q.target", "ta")->leftJoin("q.owner", "ow")->leftJoin("q.data", "da"); }
/** * @param ClientConditionInterface $condition */ protected function prepareTagsCondition(ClientConditionInterface $condition) { if ($condition->getTags() && count($condition->getTags())) { $this->qb->leftJoin('c.tags', 't'); $this->qb->andWhere($this->qb->expr()->in('t.id', ':tags'))->setParameter('tags', $condition->getTags()); } }
/** * @param QueryBuilder $qb * @return $this */ public function prepareQuery(QueryBuilder $qb) { foreach ($this->emailOwnerFieldNames as $fieldName) { $qb->leftJoin('a.' . $fieldName, $fieldName); } return $this; }
/** * Strips the key parts and creates a join if it does not exist yet. * * @param string $key */ protected function shouldJoin($key) { $parts = explode('.', $key); if (!in_array($parts[0], $this->qb->getAllAliases())) { $this->qb->leftJoin($this->getRootAlias() . '.' . $parts[0], $parts[0]); } }
/** * {@inheritdoc} * * Orders collection by properties. The order of the ordered properties is the same as the order specified in the * query. * For each property passed, if the resource does not have such property or if the order value is different from * `asc` or `desc` (case insensitive), the property is ignored. */ public function apply(ResourceInterface $resource, QueryBuilder $queryBuilder) { $request = $this->requestStack->getCurrentRequest(); if (null === $request) { return; } $properties = $this->extractProperties($request); foreach ($properties as $property => $order) { if (!$this->isPropertyEnabled($property) || !$this->isPropertyMapped($property, $resource)) { continue; } if (empty($order) && isset($this->properties[$property])) { $order = $this->properties[$property]; } $order = strtoupper($order); if (!in_array($order, ['ASC', 'DESC'])) { continue; } $alias = 'o'; $field = $property; if ($this->isPropertyNested($property)) { $propertyParts = $this->splitPropertyParts($property); $parentAlias = $alias; foreach ($propertyParts['associations'] as $association) { $alias = QueryNameGenerator::generateJoinAlias($association); $queryBuilder->leftJoin(sprintf('%s.%s', $parentAlias, $association), $alias); $parentAlias = $alias; } $field = $propertyParts['field']; } $queryBuilder->addOrderBy(sprintf('%s.%s', $alias, $field), $order); } }
/** * Prepare certain search condition * * @param \Doctrine\ORM\QueryBuilder $queryBuilder Query builder to prepare * @param mixed $value Condition data * @param boolean $countOnly "Count only" flag. Do not need to add "order by" clauses if only count is needed. * * @return void */ protected function prepareCndProduct(\Doctrine\ORM\QueryBuilder $queryBuilder, $value, $countOnly) { if ($value instanceof \XLite\Model\Product) { $queryBuilder->andWhere('w.product = :product')->setParameter('product', $value); } else { $queryBuilder->leftJoin('w.product', 'product')->andWhere('product.product_id = :productId')->setParameter('productId', $value); } }
/** * @param QueryBuilder $query * @param $source * @param $locale * @param bool $resetJoin */ public function addQueryTranslationSupport(QueryBuilder $query, $source, $locale, $resetJoin = true) { if ($resetJoin) { $query->resetDQLPart('join'); } $query->leftJoin($source->getTableAlias() . '.translations', '_translations', 'WITH', $query->expr()->orX($query->expr()->eq('_translations.locale', ':locale'), $query->expr()->isNull('_translations.id'))); $query->setParameter('locale', $locale); }
/** * @param QueryBuilder $qb Source query builder * @param string $emailFromTableAlias EmailAddress table alias of joined Email#fromEmailAddress association */ public function prepareQuery(QueryBuilder $qb, $emailFromTableAlias = 'a') { $qb->addSelect($this->getFromEmailExpression($emailFromTableAlias)); foreach ($this->emailOwnerProviderStorage->getProviders() as $provider) { $fieldName = $this->emailOwnerProviderStorage->getEmailOwnerFieldName($provider); $qb->leftJoin(sprintf('%s.%s', $emailFromTableAlias, $fieldName), $fieldName); } }
/** * {@inheritdoc} */ public function addAttributeSorter(AttributeInterface $attribute, $direction, $locale = null, $scope = null) { if (null === $locale) { throw new \InvalidArgumentException(sprintf('Cannot prepare condition on type "%s" without locale', $attribute->getAttributeType())); } $aliasPrefix = 'sorter'; // join to values $joinAlias = $aliasPrefix . 'V' . $attribute->getCode(); $condition = $this->prepareAttributeJoinCondition($attribute, $joinAlias, $locale, $scope); $this->qb->leftJoin(current($this->qb->getRootAliases()) . '.values', $joinAlias, 'WITH', $condition); // join to reference data $joinAliasOpt = $attribute->getCode(); $this->qb->leftJoin($joinAlias . '.' . $attribute->getReferenceDataName(), $joinAliasOpt); $this->qb->addOrderBy($joinAliasOpt . '.code', $direction); $idField = current($this->qb->getRootAliases()) . '.id'; $this->qb->addOrderBy($idField); return $this; }
/** * {@inheritdoc} */ protected function applyFilter(ResourceInterface $resource, QueryBuilder $queryBuilder, array $queryValues) { if (!isset($queryValues['mandate']) || !is_string($queryValues['mandate'])) { return; } $mandateId = $this->getFilterValueFromUrl($queryValues['mandate']); //TODO: secure parameters $queryBuilder->leftJoin('o.jobs', 'user_jobs_alias')->andWhere('user_jobs_alias.mandate = :user_mandate_id')->setParameter('user_mandate_id', $mandateId); }
/** * Add relations into query builder (do LEFT JOINs) * * @param QueryBuilder $qb * @param array $relations */ protected function addRelations(QueryBuilder $qb, array $relations) { $defaultJoinedRelations = $this->defaultJoinedRelations(); foreach ($relations as $relation) { if (!in_array($relation, $defaultJoinedRelations)) { $qb->leftJoin($this->processedAliases[$relation], $this->getAliasFor($relation)); } } }
/** * @param QueryBuilder $qb */ protected function prepareIteratorPart(QueryBuilder $qb) { if (!$this->unsubscribedItemClassName) { throw new \InvalidArgumentException('Unsubscribed Item Class name must be provided'); } $rootAliases = $qb->getRootAliases(); $entityAlias = reset($rootAliases); $qb->leftJoin($this->unsubscribedItemClassName, 'mlu', Join::WITH, "mlu.entityId = {$entityAlias}.id")->andWhere($qb->expr()->isNotNull('mlu.id')); }
/** * @param $columns \Sorien\DataGridBundle\Grid\Column\Column[] * @param $page int Page Number * @param $limit int Rows Per Page * @return \Sorien\DataGridBundle\Grid\Rows */ public function execute($columns, $page = 0, $limit = 0) { $this->query = $this->manager->createQueryBuilder($this->class); $this->query->from($this->class, self::TABLE_ALIAS); $where = $this->query->expr()->andx(); $sorted = false; foreach ($columns as $column) { $this->query->addSelect($this->getFieldName($column)); if ($column->isSorted() && !$column->isDefaultSort()) { $this->query->orderBy($this->getFieldName($column, false), $column->getOrder()); $sorted = true; } elseif (!$sorted && $column->isSorted() && $column->isDefaultSort()) { $this->query->orderBy($this->getFieldName($column, false), $column->getOrder()); } if ($column->isFiltered()) { if ($column->getFiltersConnection() == column::DATA_CONJUNCTION) { foreach ($column->getFilters() as $filter) { $operator = $this->normalizeOperator($filter->getOperator()); $where->add($this->query->expr()->{$operator}($this->getFieldName($column, false), $this->normalizeValue($filter->getOperator(), $filter->getValue()))); } } elseif ($column->getFiltersConnection() == column::DATA_DISJUNCTION) { $sub = $this->query->expr()->orx(); foreach ($column->getFilters() as $filter) { $operator = $this->normalizeOperator($filter->getOperator()); $sub->add($this->query->expr()->{$operator}($this->getFieldName($column, false), $this->normalizeValue($filter->getOperator(), $filter->getValue()))); } $where->add($sub); } $this->query->where($where); } } foreach ($this->joins as $alias => $field) { $this->query->leftJoin($field, $alias); } if ($page > 0) { $this->query->setFirstResult($page * $limit); } if ($limit > 0) { $this->query->setMaxResults($limit); } //call overridden prepareQuery or associated closure $query = $this->prepareQuery(clone $this->query); $items = $query->getQuery()->getResult(); // hydrate result $result = new Rows(); foreach ($items as $item) { $row = new Row(); foreach ($item as $key => $value) { $row->setField($key, $value); } //call overridden prepareRow or associated closure if (($modifiedRow = $this->prepareRow($row)) != null) { $result->addRow($modifiedRow); } } return $result; }
/** * Add completeness joins to query builder * * @param string $completenessAlias the join alias * @param string $locale the locale * @param string $scope the scope * * @return CompletenessJoin */ public function addJoins($completenessAlias, $locale, $scope) { $rootAlias = $this->qb->getRootAliases()[0]; $localeAlias = $completenessAlias . 'Locale'; $channelAlias = $completenessAlias . 'Channel'; $rootEntity = $this->qb->getRootEntities()[0]; $completenessMapping = $this->qb->getEntityManager()->getClassMetadata($rootEntity)->getAssociationMapping('completenesses'); $completenessClass = $completenessMapping['targetEntity']; $joinCondition = sprintf('%s.product = %s.id', $completenessAlias, $rootAlias); $this->qb->leftJoin('PimCatalogBundle:Channel', $channelAlias, 'WITH', $channelAlias . '.code = :cScopeCode')->setParameter('cScopeCode', $scope); $joinCondition .= sprintf(' AND %s.channel = %s.id', $completenessAlias, $channelAlias); if (null !== $locale) { $this->qb->leftJoin('PimCatalogBundle:Locale', $localeAlias, 'WITH', sprintf('%s.code = :%scLocaleCode', $localeAlias, $localeAlias))->setParameter($localeAlias . 'cLocaleCode', $locale); $joinCondition .= sprintf(' AND %s.locale = %s.id', $completenessAlias, $localeAlias); } $this->qb->leftJoin($completenessClass, $completenessAlias, 'WITH', $joinCondition); return $this; }
/** * {@inheritdoc} */ public function walkComparison(Comparison $comparison) { $value = $comparison->getValue()->getValue(); list($type, $field) = $this->explodeCombinedFieldString($comparison->getField()); $index = str_replace('.', '_', uniqid('', true)); $joinField = sprintf('search.%sFields', $type); $joinAlias = $this->driver->getJoinAlias($type, $index); $this->qb->leftJoin($joinField, $joinAlias); $searchCondition = ['fieldName' => $field, 'condition' => Criteria::getSearchOperatorByComparisonOperator($comparison->getOperator()), 'fieldValue' => $value, 'fieldType' => $type]; if ($type === Query::TYPE_TEXT) { if ($searchCondition['fieldValue'] === '') { $this->qb->setParameter('field' . $index, $searchCondition['fieldName']); return $joinAlias . '.field = :field' . $index; } else { return $this->driver->addTextField($this->qb, $index, $searchCondition, $this->setOrderBy); } } return $this->driver->addNonTextField($this->qb, $index, $searchCondition); }
private function addInclude($include) { if (!$this->hasInclude($include)) { throw new \Exception('Invalid Include: ' . $include); } if ($this->includeExists($include)) { return; } $this->qb->leftJoin('e.' . $include, $include); }
/** * Left joins relations to eager load. * * @param ResourceInterface $resource * @param QueryBuilder $queryBuilder */ private function joinRelations(ResourceInterface $resource, QueryBuilder $queryBuilder) { $classMetaData = $queryBuilder->getEntityManager()->getClassMetadata($resource->getEntityClass()); foreach ($classMetaData->getAssociationNames() as $i => $association) { $mapping = $classMetaData->associationMappings[$association]; if (ClassMetadataInfo::FETCH_EAGER === $mapping['fetch']) { $queryBuilder->leftJoin('o.' . $association, 'a' . $i); $queryBuilder->addSelect('a' . $i); } } }
/** * @param string $field * @param mixed $value * @return array */ protected function setQueryParam($field) { $index = 0; $rootAlias = $this->qb->getRootAliases()[$index]; if (false !== strpos($field, '.')) { list($assoc, $subField) = explode('.', $field); } else { $assoc = $field; } $meta = $this->getClassMetadata($index); if ($meta->hasAssociation($assoc)) { $targetClass = $meta->getAssociationTargetClass($assoc); if ($meta->isCollectionValuedAssociation($assoc)) { $alias = "{$rootAlias}_{$assoc}"; if (!in_array($alias, $this->qb->getAllAliases())) { $this->qb->leftJoin("{$rootAlias}.{$assoc}", $alias); } $assoc = $alias; } else { $alias = "{$rootAlias}_{$assoc}"; if (!in_array($alias, $this->qb->getAllAliases())) { $this->qb->join("{$rootAlias}.{$assoc}", $alias); } $assoc = $alias; } $em = $this->qb->getEntityManager(); $targetMeta = $em->getClassMetadata($targetClass); if (isset($subField) && !$targetMeta->hasField($subField) && $targetMeta->isInheritanceTypeJoined()) { foreach ($targetMeta->discriminatorMap as $alias => $class) { $joinedMeta = $em->getClassMetadata($class); if ($joinedMeta->hasField($subField)) { if (!in_array($alias, $this->qb->getAllAliases())) { $this->qb->leftJoin($joinedMeta->getName(), $alias, 'WITH', "{$alias}.id = {$assoc}.id"); } $assoc = $alias; } } } $alias = isset($subField) ? "{$assoc}.{$subField}" : $assoc; } else { $alias = "{$rootAlias}.{$field}"; } $values = array_slice(func_get_args(), 1); if ($values) { $result = [$alias]; foreach ($values as $value) { $paramName = $this->getParamName($field); $this->qb->setParameter($paramName, $value); $result[] = ":{$paramName}"; } return $result; } return $alias; }