diff --git a/src/Command/ModelCommand.php b/src/Command/ModelCommand.php index 423f088e..f90b48e5 100644 --- a/src/Command/ModelCommand.php +++ b/src/Command/ModelCommand.php @@ -1,4 +1,5 @@ ensureAliasUniqueness($associations); + foreach ($associations as $type => $assocs) { foreach ($assocs as $assoc) { $alias = $assoc['alias']; @@ -382,16 +387,19 @@ public function findBelongsTo(Table $model, array $associations, ?Arguments $arg } $assoc = [ 'alias' => $tmpModelName, + 'className' => $tmpModelName, 'foreignKey' => $fieldName, ]; if ($schema->getColumn($fieldName)['null'] === false) { $assoc['joinType'] = 'INNER'; } } - if ($this->plugin && empty($assoc['className'])) { $assoc['className'] = $this->plugin . '.' . $assoc['alias']; } + if (!empty($assoc['className'])) { + $assoc['alias'] = $assoc['className'] . '_' . $model->getAlias() . '_' . $fieldName; + } $associations['belongsTo'][] = $assoc; } @@ -708,7 +716,7 @@ public function getEntityPropertySchema(Table $model): array if ($entityClass === '\Cake\ORM\Entity') { $namespace = Configure::read('App.namespace'); - [$plugin, ] = pluginSplit($association->getTarget()->getRegistryAlias()); + [$plugin,] = pluginSplit($association->getTarget()->getRegistryAlias()); if ($plugin !== null) { $namespace = $plugin; } @@ -1352,7 +1360,7 @@ public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionPar ])->addOption('skip-relation-check', [ 'boolean' => true, 'help' => 'Generate relations for all "example_id" fields' - . ' without checking the database if a table "examples" exists.', + . ' without checking the database if a table "examples" exists.', ])->setEpilog( 'Omitting all arguments and options will list the table names you can generate models for.' ); @@ -1546,4 +1554,41 @@ protected function bakeEnums(Table $model, array $data, Arguments $args, Console $enumCommand->execute($args, $io); } } + + /** + * @param array> $associations + * @return array> + */ + protected function ensureAliasUniqueness(array $associations): array + { + $existing = []; + foreach ($associations as $type => $associationsPerType) { + foreach ($associationsPerType as $k => $association) { + $alias = $association['alias']; + if (in_array($alias, $existing, true)) { + $alias = $this->alias($association); + } + $existing[] = $alias; + if (empty($association['className'])) { + $className = $this->plugin ? $this->plugin . '.' . $association['alias'] : $association['alias']; + $association['className'] = $className; + } + $association['alias'] = $alias; + $associations[$type][$k] = $association; + } + } + + return $associations; + } + + /** + * @param array $association + * @return string + */ + protected function alias(array $association): string + { + $foreignKey = $association['foreignKey']; + + return $this->_modelNameFromKey($foreignKey); + } }