Ejemplo n.º 1
0
 /**
  * Setups a relation n-m between two models
  *
  * @param \Phalcon\Mvc\ModelInterface $model
  * @param string|array $fields
  * @param string $intermediateModel
  * @param string|array $intermediateFields
  * @param string|array $intermediateReferencedFields
  * @param string $referencedModel
  * @param string|array $referencedFields
  * @param array|null $options
  * @return \Phalcon\Mvc\Model\Relation
  * @throws Exception
  */
 public function addHasManyToMany($model, $fields, $intermediateModel, $intermediateFields, $intermediateReferencedFields, $referencedModel, $referencedFields, $options = null)
 {
     if (is_object($model) === false || $model instanceof ModelInterface === false || is_string($intermediateModel) === false || is_string($referencedModel) === false || is_array($options) === false && is_null($options) === false) {
         throw new Exception('Invalid parameter type.');
     }
     $entityName = strtolower(get_class($model));
     $intermediateEntity = strtolower($intermediateModel);
     $referencedEntity = strtolower($referencedModel);
     $keyRelation = $entityName . '$' . $referencedEntity;
     if (isset($this->_hasManyToMany[$keyRelation]) === false) {
         $relations = array();
     } else {
         $relations = $this->_hasManyToMany[$keyRelation];
     }
     //Check if the number of fields is the same from the model to the intermediate model
     if (is_array($intermediateFields) === true && count($fields) !== count($intermediateFields)) {
         throw new Exception('Number of referenced fields are not the same');
         //@note sic!
     }
     //@note this check is doing the same as the check before:
     //Check if the number of fields is the same from the intermediate model to the
     //referenced model
     //Create a relationship instance
     $relation = new Relation(4, $referencedModel, $fields, $referencedFields, $options);
     //Set extended intermediate relation data
     $relation->setIntermediateRelation($intermediateFields, $intermediateModel, $intermediateFields);
     if (isset($options['alias']) === true) {
         $lowerAlias = strtolower($options['alias']);
     } else {
         $lowerAlias = $referencedEntity;
     }
     //Append a new relationship
     $relations[] = $relation;
     //Update the global alias
     $this->_aliases[$entityName . '$' . $lowerAlias] = $relation;
     //Update the relations
     $this->_hasManyToMany[$keyRelation] = $relations;
     //Get existing relations by model
     if (isset($this->_hasManyToManySingle[$entityName]) === false) {
         $singleRelations = array();
     } else {
         $singleRelations = $this->_hasManyToManySingle[$entityName];
     }
     //Append a new relationship
     $singleRelations[] = $relation;
     //Update relations by model
     $this->_hasManyToManySingle[$entityName] = $singleRelations;
     return $relation;
 }