From e6cc13aedff7967808990a4d1bbc4e0146613323 Mon Sep 17 00:00:00 2001 From: Wolfy-J Date: Sat, 5 Mar 2016 14:55:11 +0300 Subject: [PATCH] schema aliases --- source/Spiral/ORM/Entities/SchemaBuilder.php | 61 ++++++++++++++++++-- 1 file changed, 55 insertions(+), 6 deletions(-) diff --git a/source/Spiral/ORM/Entities/SchemaBuilder.php b/source/Spiral/ORM/Entities/SchemaBuilder.php index 496f6e8f..2ecc4540 100644 --- a/source/Spiral/ORM/Entities/SchemaBuilder.php +++ b/source/Spiral/ORM/Entities/SchemaBuilder.php @@ -37,6 +37,13 @@ class SchemaBuilder extends Component */ private $tables = []; + /** + * Associations between tables and their database and original table aliases. + * + * @var array + */ + private $aliases = []; + /** * @var ORMConfig */ @@ -131,15 +138,57 @@ public function hasTable($database, $table) */ public function declareTable($database, $table) { - $database = $this->resolveDatabase($database); + $normalizedDatabase = $this->resolveDatabase($database); + + if (isset($this->tables[$normalizedDatabase . '/' . $table])) { + return $this->tables[$normalizedDatabase . '/' . $table]; + } + + $schema = $this->orm->database($normalizedDatabase)->table($table)->schema(); + + $this->aliases[] = [ + 'schema' => $schema, + 'database' => $database, + 'table' => $table + ]; - if (isset($this->tables[$database . '/' . $table])) { - return $this->tables[$database . '/' . $table]; + return $this->tables[$normalizedDatabase . '/' . $table] = $schema; + } + + /** + * Database aliases associated with given table schema. + * + * @param AbstractTable $table + * @return string + * @throws SchemaException + */ + public function databaseAlias(AbstractTable $table) + { + foreach ($this->aliases as $item) { + if ($item['schema'] === $table) { + return $item['database']; + } } - $schema = $this->orm->database($database)->table($table)->schema(); + throw new SchemaException("Unable to resolve database alias for table '{$table->getName()}'"); + } - return $this->tables[$database . '/' . $table] = $schema; + /** + * Table aliases associated with given table schema. + * + * @param AbstractTable $table + * @return string + * @throws SchemaException + */ + public function tableAlias(AbstractTable $table) + { + foreach ($this->aliases as $item) { + if ($item['schema'] === $table) { + return $item['table']; + } + } + + throw new SchemaException("Unable to resolve table alias for table '{$table->getName()}'"); } /** @@ -385,7 +434,7 @@ protected function castSchemas() foreach ($this->records as $record) { $record->castSchema(); } - + $inversedRelations = []; foreach ($this->records as $record) { if ($record->isAbstract()) {