Commit bd07bc1d by Luciano Baraglia

GII generates rules for unique indexes

parent ab05f0d7
...@@ -13,6 +13,7 @@ use yii\db\Connection; ...@@ -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.
...@@ -247,7 +248,24 @@ class Generator extends \yii\gii\Generator ...@@ -247,7 +248,24 @@ class Generator extends \yii\gii\Generator
foreach ($lengths as $length => $columns) { foreach ($lengths as $length => $columns) {
$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) {
$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;
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment