protected function addForeignKey(Object $object, RelationDefinitionInterface $relation, &$xmlTable) { $relationName = $relation->getName(); $foreignObject = $this->objects->getDefinition($relation->getForeignObjectKey()); if (!$foreignObject) { throw new ModelBuildException(sprintf('Foreign object `%s` does not exist in relation `%s`', $relation->getForeignObjectKey(), $relation->getName())); } if ($object->getStorageService() !== $foreignObject->getStorageService()) { throw new ModelBuildException(sprintf('Can not create a relation between two different dataModels. Got `%s` but `%s` is needed.', $foreignObject->getStorageService(), $object->getStorageService())); } $pluralizer = new StandardEnglishPluralizer(); $foreignPhpName = ucfirst($pluralizer->getSingularForm(lcfirst($relationName))); $foreigns = $xmlTable->xpath('foreign-key[@phpName=\'' . $foreignPhpName . '\']'); if ($foreigns) { $foreignKey = current($foreigns); } else { $foreignKey = $xmlTable->addChild('foreign-key'); } $foreignKey['phpName'] = $foreignPhpName; $foreignKey['foreignTable'] = $foreignObject->getTable(); if ($refName = $relation->getRefName()) { $foreignKey['refPhpName'] = ucfirst($pluralizer->getSingularForm(lcfirst($refName))); } $foreignKey['onDelete'] = $relation->getOnDelete(); $foreignKey['onUpdate'] = $relation->getOnUpdate(); if (!$relation->getWithConstraint()) { $foreignKey['skipSql'] = 'true'; } $references = $foreignKey->xpath("reference[not(@custom='true')]"); foreach ($references as $i => $ref) { unset($references[$i][0]); } foreach ($relation->getReferences() as $reference) { $localName = Tools::camelcase2Underscore($reference->getLocalColumn()->getName()); $references = $foreignKey->xpath('reference[@local=\'' . $localName . '\']'); if ($references) { $xmlReference = current($references); } else { $xmlReference = $foreignKey->addChild('reference'); } $xmlReference['local'] = $localName; $xmlReference['foreign'] = Tools::camelcase2Underscore($reference->getForeignColumn()->getName()); } if ($foreignObject->getWorkspace()) { if (!$object->getWorkspace()) { $columns = $xmlTable->xpath('column[@name=\'workspace_id\']'); if (!$columns) { $newCol = $xmlTable->addChild('column'); $newCol['name'] = 'workspace_id'; $newCol['type'] = 'INTEGER'; $newCol['defaultValue'] = '1'; } } $localName = 'workspace_id'; $references = $foreignKey->xpath('reference[@local=\'' . $localName . '\']'); if ($references) { $xmlReference = current($references); } else { $xmlReference = $foreignKey->addChild('reference'); } $xmlReference['local'] = $localName; $xmlReference['foreign'] = 'workspace_id'; } }
/** * @param \Jarves\Admin\FieldTypes\RelationDefinitionInterface $relation */ public function addRelation($relation) { $this->relations[strtolower($relation->getName())] = $relation; }