Skip to content

Commit

Permalink
Fix #542: Use the table name to create the relation
Browse files Browse the repository at this point in the history
  • Loading branch information
thiagotalma authored Nov 20, 2023
1 parent be02a08 commit e65f3b2
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 21 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ Yii Framework 2 gii extension Change Log

- Bug #532: Return `ExitCode::USAGE` on command input validation error (egmsystems)
- Enh #537: Generating rules for the fields with default values (manky)
- Enh #542: Use the table name to create the relation (thiagotalma)


2.2.6 May 22, 2023
Expand Down
26 changes: 6 additions & 20 deletions src/generators/model/Generator.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ class Generator extends \yii\gii\Generator
public $generateJunctionRelationMode = self::JUNCTION_RELATION_VIA_TABLE;
public $useClassConstant;
public $generateRelationsFromCurrentSchema = true;
public $generateRelationNameFromDestinationTable = false;
public $generateLabelsFromComments = false;
public $useTablePrefix = false;
public $standardizeCapitals = false;
Expand Down Expand Up @@ -130,7 +131,7 @@ public function rules()
[['generateRelations'], 'in', 'range' => [self::RELATIONS_NONE, self::RELATIONS_ALL, self::RELATIONS_ALL_INVERSE]],
[['generateJunctionRelationMode'], 'in', 'range' => [self::JUNCTION_RELATION_VIA_TABLE, self::JUNCTION_RELATION_VIA_MODEL]],
[
['generateLabelsFromComments', 'useTablePrefix', 'useSchemaName', 'generateQuery', 'generateRelationsFromCurrentSchema', 'useClassConstant', 'enableI18N', 'standardizeCapitals', 'singularize'],
['generateLabelsFromComments', 'useTablePrefix', 'useSchemaName', 'generateQuery', 'generateRelationsFromCurrentSchema', 'generateRelationNameFromDestinationTable', 'useClassConstant', 'enableI18N', 'standardizeCapitals', 'singularize'],
'boolean'
],
[['messageCategory'], 'validateMessageCategory', 'skipOnEmpty' => false],
Expand All @@ -153,6 +154,7 @@ public function attributeLabels()
'generateRelations' => 'Generate Relations',
'generateJunctionRelationMode' => 'Generate Junction Relations As',
'generateRelationsFromCurrentSchema' => 'Generate Relations from Current Schema',
'generateRelationNameFromDestinationTable' => 'Generate Relation Names Using Target Table Name',
'useClassConstant' => 'Use `::class`',
'generateLabelsFromComments' => 'Generate Labels from DB Comments',
'generateQuery' => 'Generate ActiveQuery',
Expand Down Expand Up @@ -195,6 +197,7 @@ class.',
Make sure you also generate the junction models when using the "Via Model" option.
',
'generateRelationsFromCurrentSchema' => 'This indicates whether the generator should generate relations from current schema or from all available schemas.',
'generateRelationNameFromDestinationTable' => 'This indicates whether the relation names should use target table name.',
'useClassConstant' => 'Use the `::class` constant instead of the `::className()` method.',
'generateLabelsFromComments' => 'This indicates whether the generator should generate attribute labels
by using the comments of the corresponding DB columns.',
Expand Down Expand Up @@ -438,21 +441,12 @@ public function generateRules($table)
{
$types = [];
$lengths = [];
$nullable = [];
$defaultValues = [];
foreach ($table->columns as $column) {
if ($column->autoIncrement) {
continue;
}
if (!$column->allowNull && $column->defaultValue === null) {
$types['required'][] = $column->name;
} elseif ($column->allowNull && $column->defaultValue === null) {
$nullable[] = $column->name;
} elseif (is_scalar($column->defaultValue)) {
if (array_key_exists($column->defaultValue, $defaultValues)) {
$defaultValues[$column->defaultValue] = [];
}
$defaultValues[$column->defaultValue][] = $column->name;
}
switch ($column->type) {
case Schema::TYPE_SMALLINT:
Expand Down Expand Up @@ -486,15 +480,6 @@ public function generateRules($table)
}
}
$rules = [];
if (!empty($nullable)) {
$rules[] = "[['" . implode("', '", $nullable) . "'], 'default', 'value' => null]";
}
if (!empty($defaultValues)) {
foreach ($defaultValues as $defaultValue => $defaultValueColumns) {
$defaultValue = is_numeric($defaultValue) ? $defaultValue : "'$defaultValue'";
$rules[] = "[['" . implode("', '", $defaultValueColumns) . "'], 'default', 'value' => $defaultValue]";
}
}
$driverName = $this->getDbDriverName();
foreach ($types as $type => $columns) {
if ($driverName === 'pgsql' && $type === 'integer') {
Expand Down Expand Up @@ -702,12 +687,13 @@ protected function generateRelations()
}
unset($refs[0]);
$fks = array_keys($refs);
$relName = $this->generateRelationNameFromDestinationTable ? $refTable : $fks[0];
$refClassName = $this->generateClassName($refTable);
$refClassNameResolution = $this->generateClassNameResolution($refClassName);

// Add relation for this table
$link = $this->generateRelationLink(array_flip($refs));
$relationName = $this->generateRelationName($relations, $table, $fks[0], false);
$relationName = $this->generateRelationName($relations, $table, $relName, false);
$relations[$table->fullName][$relationName] = [
"return \$this->hasOne($refClassNameResolution, $link);",
$refClassName,
Expand Down
1 change: 1 addition & 0 deletions src/generators/model/form.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
Generator::JUNCTION_RELATION_VIA_MODEL => 'Via Model',
]);
echo $form->field($generator, 'generateRelationsFromCurrentSchema')->checkbox();
echo $form->field($generator, 'generateRelationNameFromDestinationTable')->checkbox();
echo $form->field($generator, 'useClassConstant')->checkbox();
echo $form->field($generator, 'generateLabelsFromComments')->checkbox();
echo $form->field($generator, 'generateQuery')->checkbox();
Expand Down
27 changes: 26 additions & 1 deletion tests/generators/ModelGeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,20 @@ public function relationsProvider()
'expected' => true,
],
]],
['product_language', 'ProductLanguage.php', false, [
[
'name' => 'function getProduct()',
'relation' => "\$this->hasOne(Product::className(), ['supplier_id' => 'supplier_id', 'id' => 'id']);",
'expected' => true,
],
[
'name' => 'function getSupplier()',
'relation' => "\$this->hasOne(Supplier::className(), ['id' => 'supplier_id']);",
'expected' => true,
],
],
true // $fromDestTable
],

['organization', 'Organization.php', false, [
[
Expand Down Expand Up @@ -174,6 +188,15 @@ public function relationsProvider()
'expected' => true,
],
]],
['blog_rtl', 'BlogRtl.php', false, [
[
'name' => 'function getUserRtl()',
'relation' => "\$this->hasOne(UserRtl::className(), ['id' => 'id_user']);",
'expected' => true,
],
],
true
],

// useClassConstant = true
['category', 'Category.php', true, [
Expand All @@ -197,12 +220,14 @@ public function relationsProvider()
* @param $fileName string
* @param $useClassConstant bool
* @param $relations array
* @param $fromDestTable bool
*/
public function testRelations($tableName, $fileName, $useClassConstant, $relations)
public function testRelations($tableName, $fileName, $useClassConstant, $relations, $fromDestTable = false)
{
$generator = new ModelGenerator();
$generator->template = 'default';
$generator->generateRelationsFromCurrentSchema = false;
$generator->generateRelationNameFromDestinationTable = $fromDestTable;
$generator->useClassConstant = $useClassConstant;
$generator->tableName = $tableName;

Expand Down

0 comments on commit e65f3b2

Please sign in to comment.