Ejemplo n.º 1
0
 /**
  * Gets query for loading related records
  *
  * @param  Record $record
  * @param  string $relationName
  * @param  array  $identifiers
  * @return \Dive\Query\Query
  */
 private function getReferenceQuery(Record $record, $relationName, array $identifiers = array())
 {
     if (empty($identifiers)) {
         $identifiers = array($record->getStoredIdentifierAsString());
     }
     $table = $record->getTable();
     $rm = $table->getRecordManager();
     $relatedTable = $this->getJoinTable($rm, $relationName);
     $query = $relatedTable->createQuery('a');
     $query->distinct();
     if ($this->isReferencedSide($relationName)) {
         $expression = $table->getIdentifierQueryExpression('b');
         $query->leftJoin("a.{$this->owningAlias} b")->whereIn($expression, $identifiers);
     } else {
         $connection = $table->getConnection();
         $expression = $connection->quoteIdentifier("a.{$this->owningField}");
         $query->whereIn($expression, $identifiers);
         if ($this->isOneToMany() && $this->orderBy) {
             if (false !== ($pos = strpos($this->orderBy, '.'))) {
                 list($orderByRelationAlias, $orderByField) = explode('.', $this->orderBy);
                 $query->leftJoin("a.{$orderByRelationAlias} b")->orderBy("b.{$orderByField}");
             } else {
                 if ($relatedTable->hasField($this->orderBy)) {
                     $query->orderBy("a.{$this->orderBy}");
                 }
             }
         }
     }
     return $query;
 }