@param $entityName
@param $where
@param array $joinConditions

@return int
12108
public function getTotalNumberOfElements($entityName, $where, $joinConditions = [])
    {
        $this->totalNumberOfElements = $this->getRepository($entityName)->getCount($where, $joinConditions);

        return $this->totalNumberOfElements;
    }
612441
protected function getManyToManyRelationSelectSQL(RelationDescription $relationDescription,
          array $otherObjectProxies, $otherRole, $criteria=null, $orderby=null,
          PagingInfo $pagingInfo=null) {
    $thisRelationDesc = $relationDescription->getThisEndRelation();
    $otherRelationDesc = $relationDescription->getOtherEndRelation();
    $nmMapper = self::getMapper($thisRelationDesc->getOtherType());
    $otherFkAttr = $nmMapper->getAttribute($otherRelationDesc->getFkName());
    $nmTableName = $nmMapper->getRealTableName();

    // id parameters
    $parameters = [];
    $idPlaceholder = ':'.$nmTableName.'_'.$otherFkAttr->getName();
    for ($i=0, $count=sizeof($otherObjectProxies); $i<$count; $i++) {
      $dbid = $otherObjectProxies[$i]->getValue($otherRelationDesc->getIdName());
      if ($dbid === null) {
        $dbid = SQLConst::NULL();
      }
      $parameters[$idPlaceholder.$i] = $dbid;
    }

    // statement
    $queryId = $this->getCacheKey($otherRole.sizeof($otherObjectProxies), null, $criteria, $orderby, $pagingInfo);
    $selectStmt = SelectStatement::get($this, $queryId);
    if (!$selectStmt->isCached()) {
      // initialize the statement

      $thisFkAttr = $nmMapper->getAttribute($thisRelationDesc->getFkName());
      $thisIdAttr = $this->getAttribute($thisRelationDesc->getIdName());

      $tableName = $this->getRealTableName();
      $selectStmt->from($tableName, '');
      $this->addColumns($selectStmt, $tableName);
      $joinCond = $nmTableName.'.'.$thisFkAttr->getColumn().'='.$tableName.'.'.$thisIdAttr->getColumn();
      $joinColumns = [];
      $selectStmt->where($this->quoteIdentifier($nmTableName).'.'.
          $this->quoteIdentifier($otherFkAttr->getColumn()).' IN('.join(',', array_keys($parameters)).')');
      // order (in this case we use the order of the many to many objects)
      $nmSortDefs = $nmMapper->getDefaultOrder($otherRole);
      $hasNmOrder = sizeof($nmSortDefs) > 0;
      $orderType = $hasNmOrder ? $nmMapper->getType() : $this->getType();
      $orderTable = $hasNmOrder ? $nmTableName : $tableName;
      $defaultOrderDef = $hasNmOrder ? $nmSortDefs : $this->getDefaultOrder($otherRole);
      $this->addOrderBy($selectStmt, $orderby, $orderType, $orderTable, $defaultOrderDef);
      foreach($nmSortDefs as $nmSortDef) {
        // add the sort attribute from the many to many object
        $nmSortAttributeDesc = $nmMapper->getAttribute($nmSortDef['sortFieldName']);
        $joinColumns[$nmSortAttributeDesc->getName()] = $nmSortAttributeDesc->getColumn();
      }
      // add proxy id
      $joinColumns[self::INTERNAL_VALUE_PREFIX.'id'] = $otherFkAttr->getColumn();
      $selectStmt->join($nmTableName, $joinCond, $joinColumns);
      // additional conditions
      $parameters = array_merge($parameters, $this->addCriteria($selectStmt, $criteria, $nmTableName));
      // limit
      if ($pagingInfo != null) {
        $selectStmt->limit($pagingInfo->getPageSize());
      }
    }
    else {
      // on used statements only set parameters
      $parameters = array_merge($parameters, $this->getParameters($criteria, $nmTableName));
    }

    // set parameters
    $selectStmt->setParameters($parameters);

    // always update offset, since it's most likely not contained in the cache id
    if ($pagingInfo != null) {
      $selectStmt->offset($pagingInfo->getOffset());
    }
    return [$selectStmt, $otherRelationDesc->getIdName(), self::INTERNAL_VALUE_PREFIX.'id'];
  }
757419
protected function getSelectJoinColumnSQL($tableAlias, $joinColumnName, $className, $type)
    {
        $columnAlias = $this->getSQLColumnAlias($joinColumnName);

        $this->currentPersisterContext->rsm->addMetaResult('r', $columnAlias, $joinColumnName, false, $type);

        return $tableAlias . '.' . $joinColumnName . ' AS ' . $columnAlias;
    }
276879
public function search($conditions = [], $sorts = [], $joins = [], $pager = null, $mode = 'and')
    {
        $queryBuilder = $this->createQueryBuilder('o')->select('o');

        $this->queryBuilderConditions($queryBuilder, $conditions, $mode);
        $this->queryBuilderSorts($queryBuilder, $sorts);
        $this->queryBuilderJoins($queryBuilder, $joins);
        $this->queryBuilderPager($queryBuilder, $pager);

        return $queryBuilder->getQuery()->getResult();
    }
382896
protected function getManyToOneRelationSelectSQL(RelationDescription $relationDescription,
          array $otherObjectProxies, $otherRole, $criteria=null, $orderby=null,
          PagingInfo $pagingInfo=null) {
    $thisAttr = $this->getAttribute($relationDescription->getFkName());
    $tableName = $this->getRealTableName();

    // id parameters
    $parameters = [];
    $idPlaceholder = ':'.$tableName.'_'.$thisAttr->getName();
    for ($i=0, $count=sizeof($otherObjectProxies); $i<$count; $i++) {
      $dbid = $otherObjectProxies[$i]->getValue($relationDescription->getIdName());
      if ($dbid === null) {
        $dbid = SQLConst::NULL();
      }
      $parameters[$idPlaceholder.$i] = $dbid;
    }

    // statement
    $selectStmt = $this->getRelationStatement($thisAttr, $parameters,
          $otherObjectProxies, $otherRole, $criteria, $orderby, $pagingInfo);
    return [$selectStmt, $relationDescription->getIdName(), $relationDescription->getFkName()];
  }
1070798
public function buildDSRetrievalSQL($data, &$joins, &$where, $andOperation = false)
    {
        $field_id = $this->get('id');

        if (self::isFilterRegex($data[0])) {
            $this->buildRegexSQL($data[0], array('value'), $joins, $where);
        } elseif (self::isFilterSQL($data[0])) {
            $this->buildFilterSQL($data[0], array('value'), $joins, $where);
        } else {
            if (is_array($data)) {
                $data = $data[0];
            }

            $this->_key++;
            $data = $this->cleanValue($data);
            $joins .= "
                LEFT JOIN
                    `tbl_entries_data_{$field_id}` AS t{$field_id}_{$this->_key}
                    ON (e.id = t{$field_id}_{$this->_key}.entry_id)
            ";
            $where .= "
                AND MATCH (t{$field_id}_{$this->_key}.value) AGAINST ('{$data}' IN BOOLEAN MODE)
            ";
        }

        return true;
    }
1232132
public function fromToSql(?JoinClauseStrategy $join = null, bool $useClause = true): array
    {
        $params = [];

        $sql = [];

        foreach ($this->from as $from) {
            $from = $this->prepareFrom($from);

            $sqlPart = $from['table'];

            $from['alias'] && $sqlPart .= ' AS ' . $from['alias'];

            $params = array_merge($params, $from['params']);

            if ($join) {
                list($joinSql, $joinParams) = $join->joinToSql($from['tableKey']);

                if ($joinSql) {
                    $sqlPart .= ' ' . $joinSql;

                    $params = array_merge($params, $joinParams);
                }
            }

            $sql[] = $sqlPart;
        }

        $sql = implode(', ', $sql);

        if ($sql and $useClause) {
            $sql = 'FROM ' . $sql;
        }

        return [$sql, $params];
    }
1256342
public function doJoin($joinType, $table, $alias = null, $joinOn = null)
    {
        $this->joinTables[] = $tableObject = $this->createTable($table, $alias);

        $joinMetadata = new JoinMetadata();
        $joinMetadata->setJoinType($joinType);

        if ($joinOn) {
            $relativeOn = new RelativeClause($tableObject, $joinOn, RelativeClause::SELF_DIRECTIVE);
            $joinMetadata->setJoinOn($relativeOn);
        }

        $tableObject->setJoinMetadata($joinMetadata);
        is_callable($table) && $table($tableObject, $joinMetadata);

        return $tableObject;
    }
1310996
protected function createQueryBuilder($joins = null)
    {
        $this->queryBuilder = $this->em->createQueryBuilder()
            ->from($this->entityName, $this->encodeAlias($this->entityName));

        $this->assignJoins($this->queryBuilder, $joins);

        if (null !== $this->ids) {
            $this->in($this->idField, !empty($this->ids) ? $this->ids : [null]);
        }

        if (null !== $this->excludedIds && !empty($this->excludedIds)) {
            $this->notIn($this->idField, $this->excludedIds);
        }

        // set expressions
        if (!empty($this->expressions)) {
            foreach ($this->expressions as $expression) {
                $this->queryBuilder->andWhere('(' . $expression->getStatement($this->queryBuilder) . ')');
            }
        }

        $this->assignGroupBy($this->queryBuilder);

        if (null !== $this->search) {
            $searchParts = [];
            foreach ($this->searchFields as $searchField) {
                $searchParts[] = $searchField->getSearch();
            }

            $this->queryBuilder->andWhere('(' . implode(' OR ', $searchParts) . ')');
            $this->queryBuilder->setParameter('search', '%' . str_replace('*', '%', $this->search) . '%');
        }

        return $this->queryBuilder;
    }
1216753
public function mergeWheres($wheres, $bindings)
    {
        $this->wheres = array_merge((array) $this->wheres, (array) $wheres);

        $this->bindings['where'] = array_values(array_merge($this->bindings['where'], (array) $bindings));
    }
633476
public WhereCondition WHERE(WhereCondition whereCondition) {
        checkTokenOrderIsCorrect(ESqlToken.WHERE);
        mSgSQL.append("(");
        mSgSQL.append(whereCondition.toWhereConditionPart());
        mSgSQL.append(")");
        return WhereCondition.this;
    }
755627
public static function deleteWhere (string $column, array $operatorValue, string $joinOperator="AND") : bool
	{
		$joinOperator 	= static::validateOperator($joinOperator, "AND");
		$expression 	= static::generateValue($column, $operatorValue, $joinOperator);
		$sqlQuery  		= "DELETE FROM ".static::$tableName." WHERE {$column} {$expression}";
        $dbObject  		= Database::getInstance();
		$dbObject->query($sqlQuery);
		static::$affectedRows = $dbObject->affectedRows();
		return ($dbObject->affectedRows() > 0) ? TRUE : FALSE;
	}
1023997
private function applyJoinsAndFilters(ClassMetadata $metadata, string $alias, InputObjectType $typeFields, array $joins, array $conditions): void
    {
        $this->applyJoins($metadata, $joins, $alias);
        $this->collectDqlConditions($metadata, $conditions, $typeFields, $alias);
    }
571776
public function joinFrom($model, $thisKeyCol, $thatKeyCol=null, $conditions='')
	{
		if( $thatKeyCol===null )
		{
			debug_assert( $thisKeyCol!==null );
			$thatKeyCol = $model->getPrimaryKey();
		}
		elseif( $thisKeyCol===null )
		{
			debug_assert( $thatKeyCol!==null );
			$thisKeyCol = $this->getPrimaryKey();
		}

		$this->prefixColumn($model, $thatKeyCol);
		$this->prefixColumn($this, $thisKeyCol);

		$conditions = str_replace('{that}', $model->getAlias(), $conditions);
		$conditions = str_replace('{this}', $this->getAlias(), $conditions);

		$this->mapPartWhere( $this->addAliasToConditionDg() );
		$model->mapPartWhere( $model->addAliasToConditionDg() );

		$thisFrom = $this->_select->getPart(Zend_Db_Select::FROM);
		$modelColumns = array_chain(
			$model->_select->getPart(Zend_Db_Select::COLUMNS),
			array_group_dg( array_get_dg(return_dg(0)) ),
			array_map_val_dg(
				array_chain_dg(
					array_map_val_dg(
						function($descriptor)
						{
							return null===$descriptor[2]
								? $descriptor[1]
								: [ $descriptor[2] => $descriptor[1] ]
							;
						}
					),
					function($columns){
						$outArray = [];
						array_map_val($columns, function($column)use(&$outArray){
							if(is_array($column))
							{
								array_map_val($column, function($column, $alias)use(&$outArray){
									$outArray[$alias] = $column;
								});
							}
							else
							{
								$outArray[] = $column;
							}
						});
						
						return $outArray;
					}
				)
			)
		);

		array_each(
			$model->_select->getPart(Zend_Db_Select::FROM),
			function( $descriptor, $alias )use($modelColumns,$thisFrom,$model,$thisKeyCol,$thatKeyCol,$conditions)
			{
				debug_enforce(
					!array_key_exists( $alias, $thisFrom ),
					"Alias `{$alias}` already used for table `{$descriptor['tableName']}`"
				);

				switch( $descriptor['joinType'] )
				{
					case Zend_Db_Select::FROM:
						$this->_select->joinLeft(
							[$model->getAlias()=>$model->getTable()],
							"{$thisKeyCol}={$thatKeyCol} ".$conditions,
							array_key_exists( $alias, $modelColumns ) ? $modelColumns[ $alias ] : [],
							$descriptor[ 'schema' ]
						);
					break;
					case Zend_Db_Select::INNER_JOIN:
						$this->_select->joinInner(
							[$alias=>$descriptor['tableName']],
							$descriptor['joinCondition'],
							array_key_exists( $alias, $modelColumns ) ? $modelColumns[ $alias ] : [],
							$descriptor['schema']
						);
					break;
					case Zend_Db_Select::LEFT_JOIN:
						$this->_select->joinLeft(
							[$alias=>$descriptor['tableName']],
							$descriptor['joinCondition'],
							array_key_exists( $alias, $modelColumns ) ? $modelColumns[ $alias ] : [],
							$descriptor['schema']
						);
					break;
					case Zend_Db_Select::RIGHT_JOIN:
						$this->_select->joinRight(
							[$alias=>$descriptor['tableName']],
							$descriptor['joinCondition'],
							array_key_exists( $alias, $modelColumns ) ? $modelColumns[ $alias ] : [],
							$descriptor['schema']
						);
					break;
					case Zend_Db_Select::FULL_JOIN:
						$this->_select->joinFull(
							[$alias=>$descriptor['tableName']],
							$descriptor['joinCondition'],
							array_key_exists( $alias, $modelColumns ) ? $modelColumns[ $alias ] : [],
							$descriptor['schema']
						);
					break;
					case Zend_Db_Select::CROSS_JOIN:
						$this->_select->joinCross(
							[$alias=>$descriptor['tableName']],
							$descriptor['joinCondition'],
							array_key_exists( $alias, $modelColumns ) ? $modelColumns[ $alias ] : [],
							$descriptor['schema']
						);
					break;
					case Zend_Db_Select::NATURAL_JOIN:
						$this->_select->joinNatural(
							[$alias=>$descriptor['tableName']],
							$descriptor['joinCondition'],
							array_key_exists( $alias, $modelColumns ) ? $modelColumns[ $alias ] : [],
							$descriptor['schema']
						);
					break;
					default:
						debug_assert( false, "Unknown join type ".var_dump_human_compact($descriptor['joinType']));
					break;
				}
			}
		);

		$this->settingsJoin($model);

		return $this;
	}
557814
protected function doJoins($source, $joins, &$dest, $from, $contextAlias, $buildImpactIndex=true)
    {
        // expand sequences before doing any joins...
        $this->expandSequence($joins,$source);

        foreach ($joins as $predicate=>$ruleset) {
            if ($predicate=='followSequence') {
                continue;
            }

            if (isset($source[$predicate]))
            {
                // todo: perhaps we can get better performance by detecting whether or not
                // the uri to join on is already in the impact index, and if so not attempting
                // to join on it. However, we need to think about different combinations of
                // nested joins in different points of the view spec and see if this would
                // complicate things. Needs a unit test or two.
                $joinUris = [];
                if (isset($source[$predicate][VALUE_URI]))
                {
                    // single value for join
                    $joinUris[] = array(_ID_RESOURCE=>$source[$predicate][VALUE_URI],_ID_CONTEXT=>$contextAlias);
                }
                else
                {
                    // multiple values for join
                    $joinsPushed = 0;
                    foreach ($source[$predicate] as $v)
                    {
                        if (isset($ruleset['maxJoins']) && !$joinsPushed<$ruleset['maxJoins'])
                        {
                            break; // maxJoins reached
                        }
                        $joinUris[] = array(_ID_RESOURCE=>$v[VALUE_URI],_ID_CONTEXT=>$contextAlias);
                        $joinsPushed++;
                    }
                }

                $recursiveJoins = [];
                $collection = (
                isset($ruleset['from'])
                    ? $this->config->getCollectionForCBD($this->storeName, $ruleset['from'])
                    : $this->config->getCollectionForCBD($this->storeName, $from)
                );

                $cursor = $collection->find(array('_id'=>array('$in'=>$joinUris)), array(
                    'maxTimeMS' => $this->getConfigInstance()->getMongoCursorTimeout()
                ));

                $this->addIdToImpactIndex($joinUris, $dest, $buildImpactIndex);
                foreach($cursor as $linkMatch) {
                    // if there is a condition, check it...
                    if (isset($ruleset['condition']))
                    {
                        $ruleset['condition']['._id'] = $linkMatch['_id'];
                    }
                    if (!(isset($ruleset['condition']) && $collection->count($ruleset['condition'])==0))
                    {
                        // make sure any sequences are expanded before extracting properties
                        if (isset($ruleset['joins'])) $this->expandSequence($ruleset['joins'],$linkMatch);
                        if (isset($ruleset['filter']))
                        {
                            foreach($ruleset['filter'] as $filterPredicate => $filter)
                            {
                                foreach($filter as $filterType => $filterMatch)
                                {
                                    if (isset($linkMatch[$filterPredicate]))
                                    {
                                        foreach($linkMatch[$filterPredicate] as $linkMatchType => $linkMatchValues)
                                        {
                                            if (is_array($linkMatchValues) == false)
                                            {
                                                $linkMatchValues = array($linkMatchType => $linkMatchValues);
                                            }
                                            foreach($linkMatchValues as $linkMatchType => $linkMatchValue)
                                            {
                                                if ($this->matchesFilter($linkMatchType, $linkMatchValue, $filterType, $filterMatch))
                                                {
                                                    $dest[_GRAPHS][] = $this->extractProperties($linkMatch,$ruleset,$from);
                                                }
                                            }

                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            $dest[_GRAPHS][] = $this->extractProperties($linkMatch,$ruleset,$from);
                        }

                        if (isset($ruleset['joins']))
                        {
                            // recursive joins must be done after this cursor has completed, otherwise things get messy
                            $recursiveJoins[] = array('data'=>$linkMatch, 'ruleset'=>$ruleset['joins']);
                        }
                    }
                }
                if (count($recursiveJoins)>0)
                {
                    foreach ($recursiveJoins as $r)
                    {
                        $this->doJoins($r['data'],$r['ruleset'],$dest,$from,$contextAlias,$buildImpactIndex);
                    }
                }
            }
        }
        return;
    }
1142125
public function countKstruktursRelatedBySkillId(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null)
    {
        $partial = $this->collKstruktursRelatedBySkillIdPartial && !$this->isNew();
        if (null === $this->collKstruktursRelatedBySkillId || null !== $criteria || $partial) {
            if ($this->isNew() && null === $this->collKstruktursRelatedBySkillId) {
                return 0;
            }

            if ($partial && !$criteria) {
                return count($this->getKstruktursRelatedBySkillId());
            }

            $query = ChildKstrukturQuery::create(null, $criteria);
            if ($distinct) {
                $query->distinct();
            }

            return $query
                ->filterBySkillRelatedBySkillId($this)
                ->count($con);
        }

        return count($this->collKstruktursRelatedBySkillId);
    }
528176
private function createLoadContentInfoQueryBuilder(bool $joinMainLocation = true): DoctrineQueryBuilder
    {
        $queryBuilder = $this->connection->createQueryBuilder();
        $expr = $queryBuilder->expr();

        $joinCondition = $expr->eq('c.id', 't.contentobject_id');
        if ($joinMainLocation) {
            // wrap join condition with AND operator and join by a Main Location
            $joinCondition = $expr->andX(
                $joinCondition,
                $expr->eq('t.node_id', 't.main_node_id')
            );
        }

        $queryBuilder
            ->select('c.*', 't.main_node_id AS ezcontentobject_tree_main_node_id')
            ->from('ezcontentobject', 'c')
            ->leftJoin(
                'c',
                'ezcontentobject_tree',
                't',
                $joinCondition
            );

        return $queryBuilder;
    }