예제 #1
0
 /**
  * load the query object for a hasManyToMany relationship
  * build most of the joins manually since by reference relationship in the model isn't working so well
  * this support joins to distant tables with parent models
  *
  * @param Relation|PhalconRelation $relation
  * @return array
  */
 protected function getHasManyToManyRecords($relation)
 {
     $refModelNameSpace = $relation->getReferencedModel();
     $intermediateModelNameSpace = $relation->getIntermediateModel();
     // determine the key to search against
     $field = $relation->getFields();
     $referencedField = $relation->getReferencedFields();
     $intermediateFields = $relation->getIntermediateReferencedFields();
     $config = $this->getDI()->get('config');
     $modelNameSpace = $config['namespaces']['models'];
     $mm = $this->getDI()->get('modelsManager');
     /** @var Builder $query */
     $query = $mm->createBuilder()->from($intermediateModelNameSpace)->join($refModelNameSpace, $refModelNameSpace . ".{$referencedField} = " . $intermediateModelNameSpace . ".{$intermediateFields}");
     $columns = array();
     // join in parent record if one is detected
     $parentName = $relation->getParent();
     if ($parentName) {
         // load parent model
         /** @var BaseModel $parentModel */
         $parentModelNameSpace = $modelNameSpace . $parentName;
         $parentModel = new $refModelNameSpace();
         // load reference relationship
         $parentRelationship = $parentModel->getRelation($parentName);
         $columns[] = "{$parentModelNameSpace}.*";
         $query->join($parentModelNameSpace, "{$parentModelNameSpace}." . $parentRelationship->getReferencedFields() . " = {$refModelNameSpace}." . $parentRelationship->getFields(), $parentModelNameSpace);
     }
     // Load the main record field at the end, so they are not overwritten
     $columns[] = $refModelNameSpace . ".*, " . $intermediateModelNameSpace . ".*";
     $query->columns($columns);
     if (isset($this->baseRecord[$field])) {
         $fieldValue = $this->baseRecord[$field];
     } else {
         // fall back to using the primaryKeyValue
         $fieldValue = $this->primaryKeyValue;
     }
     $whereField = $intermediateModelNameSpace . '.' . $relation->getIntermediateFields();
     $query->where("{$whereField} = \"{$fieldValue}\"");
     $result = $query->getQuery()->execute();
     return $this->loadRelationRecords($result, $relation);
 }