Browse Source

Merge pull request #1624 from lucianobaraglia/master

GII generates rules for unique indexes
tags/2.0.0-beta
Qiang Xue 11 years ago
parent
commit
fc19ebdf80
  1. 40
      extensions/yii/gii/generators/model/Generator.php

40
extensions/yii/gii/generators/model/Generator.php

@ -13,6 +13,7 @@ use yii\db\Connection;
use yii\db\Schema; use yii\db\Schema;
use yii\gii\CodeFile; use yii\gii\CodeFile;
use yii\helpers\Inflector; use yii\helpers\Inflector;
use yii\base\NotSupportedException;
/** /**
* This generator will generate one or multiple ActiveRecord classes for the specified database table. * This generator will generate one or multiple ActiveRecord classes for the specified database table.
@ -239,7 +240,6 @@ class Generator extends \yii\gii\Generator
} }
} }
} }
$rules = []; $rules = [];
foreach ($types as $type => $columns) { foreach ($types as $type => $columns) {
$rules[] = "[['" . implode("', '", $columns) . "'], '$type']"; $rules[] = "[['" . implode("', '", $columns) . "'], '$type']";
@ -248,6 +248,28 @@ class Generator extends \yii\gii\Generator
$rules[] = "[['" . implode("', '", $columns) . "'], 'string', 'max' => $length]"; $rules[] = "[['" . implode("', '", $columns) . "'], 'string', 'max' => $length]";
} }
// Unique indexes rules
try {
$db = $this->getDbConnection();
$uniqueIndexes = $db->getSchema()->findUniqueIndexes($table);
foreach ($uniqueIndexes as $indexName => $uniqueColumns) {
// Avoid validating auto incrementable columns
if (!$this->isUniqueColumnAutoIncrementable($table, $uniqueColumns)) {
$attributesCount = count($uniqueColumns);
if ($attributesCount == 1) {
$rules[] = "[['" . $uniqueColumns[0] . "'], 'unique']";
} elseif ($attributesCount > 1) {
$labels = array_intersect_key($this->generateLabels($table), array_flip($uniqueColumns));
$lastLabel = array_pop($labels);
$columnsList = implode("', '", $uniqueColumns);
$rules[] = "[['" . $columnsList . "'], 'unique', 'targetAttribute' => ['" . $columnsList . "'], 'message' => 'The combination of " . implode(', ', $labels) . " and " . $lastLabel . " has already been taken.']";
}
}
}
} catch (NotSupportedException $e) {
// doesn't support unique indexes information...do nothing
}
return $rules; return $rules;
} }
@ -552,4 +574,20 @@ class Generator extends \yii\gii\Generator
{ {
return Yii::$app->{$this->db}; return Yii::$app->{$this->db};
} }
/**
* Checks if any of the specified columns of an unique index is auto incrementable.
* @param \yii\db\TableSchema $table the table schema
* @param array $columns columns to check for autoIncrement property
* @return boolean whether any of the specified columns is auto incrementable.
*/
protected function isUniqueColumnAutoIncrementable($table, $columns)
{
foreach ($columns as $column) {
if ($table->columns[$column]->autoIncrement) {
return true;
}
}
return false;
}
} }

Loading…
Cancel
Save