protected function generateRelations()
{
if (!$this->generateRelations === self::RELATIONS_NONE) {
return [];
}
$db = $this->getDbConnection();
$relations = [];
foreach ($this->getSchemaNames() as $schemaName) {
foreach ($db->getSchema()->getTableSchemas($schemaName) as $table) {
$className = $this->generateClassName($table->fullName);
foreach ($table->foreignKeys as $refs) {
$refTable = $refs[0];
$refTableSchema = $db->getTableSchema($refTable);
if ($refTableSchema === null) {
// Foreign key could point to non-existing table: https://github.com/yiisoft/yii2-gii/issues/34
continue;
}
unset($refs[0]);
$fks = array_keys($refs);
$refClassName = $this->generateClassName($refTable);
// Add relation for this table
$link = $this->generateRelationLink(array_flip($refs));
$relationName = $this->generateRelationName($relations, $table, $fks[0], false);
$relFK = key($refs);
$relations[$table->fullName][lcfirst($relationName)] = [self::REL_TYPE => "return \$this->hasOne(\\{$this->nsModel}\\{$refClassName}::className(), {$link});", self::REL_CLASS => $refClassName, self::REL_IS_MULTIPLE => 0, self::REL_TABLE => $refTable, self::REL_PRIMARY_KEY => $refs[$relFK], self::REL_FOREIGN_KEY => $relFK, self::REL_IS_MASTER => in_array($relFK, $table->getColumnNames()) ? 1 : 0];
// Add relation for the referenced table
$hasMany = $this->isHasManyRelation($table, $fks);
$link = $this->generateRelationLink($refs);
$relationName = $this->generateRelationName($relations, $refTableSchema, $className, $hasMany);
$relations[$refTableSchema->fullName][lcfirst($relationName)] = [self::REL_TYPE => "return \$this->" . ($hasMany ? 'hasMany' : 'hasOne') . "(\\{$this->nsModel}\\{$className}::className(), {$link});", self::REL_CLASS => $className, self::REL_IS_MULTIPLE => $hasMany, self::REL_TABLE => $table->fullName, self::REL_PRIMARY_KEY => $refs[key($refs)], self::REL_FOREIGN_KEY => key($refs), self::REL_IS_MASTER => in_array($relFK, $refTableSchema->getColumnNames()) ? 1 : 0];
}
if (($junctionFks = $this->checkPivotTable($table)) === false) {
continue;
}
$relations = $this->generateManyManyRelations($table, $junctionFks, $relations);
}
}
if ($this->generateRelations === self::RELATIONS_ALL_INVERSE) {
return $this->addInverseRelations($relations);
}
return $relations;
}