RainLab\Builder\Classes\TableMigrationCodeGenerator::createOrUpdateTable PHP Method

createOrUpdateTable() public method

Generates code for creating or updating a database table.
public createOrUpdateTable ( Doctrine\DBAL\Schema\Table $updatedTable, Doctrine\DBAL\Schema\Table $existingTable, string $newTableName ) : string | boolean
$updatedTable Doctrine\DBAL\Schema\Table Specifies the updated table schema.
$existingTable Doctrine\DBAL\Schema\Table Specifies the existing table schema, if applicable.
$newTableName string An updated name of the theme.
return string | boolean Returns the migration up() and down() methods code. Returns false if there the table was not changed.
    public function createOrUpdateTable($updatedTable, $existingTable, $newTableName)
    {
        $tableDiff = false;
        if ($existingTable !== null) {
            /*
             * The table already exists
             */
            $comparator = new Comparator();
            $tableDiff = $comparator->diffTable($existingTable, $updatedTable);
            if ($newTableName !== $existingTable->getName()) {
                if (!$tableDiff) {
                    $tableDiff = new TableDiff($existingTable->getName());
                }
                $tableDiff->newName = $newTableName;
            }
        } else {
            /*
             * The table doesn't exist
             */
            $tableDiff = new TableDiff($updatedTable->getName(), $updatedTable->getColumns(), [], [], $updatedTable->getIndexes());
            $tableDiff->fromTable = $updatedTable;
        }
        if (!$tableDiff) {
            return false;
        }
        if (!$this->tableHasNameOrColumnChanges($tableDiff) && !$this->tableHasPrimaryKeyChanges($tableDiff)) {
            return false;
        }
        return $this->generateCreateOrUpdateCode($tableDiff, !$existingTable, $updatedTable);
    }

Usage Example

コード例 #1
0
 public function generateCreateOrUpdateMigration()
 {
     $schemaCreator = new DatabaseTableSchemaCreator();
     $existingSchema = $this->tableInfo;
     $newTableName = $this->name;
     $tableName = $existingSchema ? $existingSchema->getName() : $this->name;
     $newSchema = $schemaCreator->createTableSchema($tableName, $this->columns);
     $codeGenerator = new TableMigrationCodeGenerator();
     $migrationCode = $codeGenerator->createOrUpdateTable($newSchema, $existingSchema, $newTableName);
     if ($migrationCode === false) {
         return $migrationCode;
     }
     $description = $existingSchema ? 'Updated table %s' : 'Created table %s';
     return $this->createMigrationObject($migrationCode, sprintf($description, $tableName));
 }