app/DoctrineMigrations/Version20251110000000.php line 1

Open in your IDE?
  1. <?php
    
    declare(strict_types=1);
    
    namespace DoctrineMigrations;
    
    use Doctrine\DBAL\Schema\Schema;
    use Doctrine\Migrations\AbstractMigration;
    
    /**
     * フリー項目1,2に制限文字数カラムを追加
     */
    final class Version20251110000000 extends AbstractMigration
    {
        public function getDescription(): string
        {
            return 'dtb_schoolテーブルにfreeitem1_max_lengthとfreeitem2_max_lengthカラムを追加';
        }
    
        public function up(Schema $schema): void
        {
            $schemaManager = $this->connection->createSchemaManager();
            
            // テーブルが存在するかチェック
            if (!$schemaManager->tablesExist(['dtb_school'])) {
                return;
            }
            
            $columns = $schemaManager->listTableColumns('dtb_school');
            $columnNames = array_map(function($column) {
                return $column->getName();
            }, $columns);
            
            // freeitem1_max_lengthカラムが存在しない場合のみ追加
            if (!in_array('freeitem1_max_length', $columnNames)) {
                // freeitem1_max_lengthカラムを追加
                $this->addSql('ALTER TABLE dtb_school ADD freeitem1_max_length INT UNSIGNED DEFAULT NULL COMMENT \'フリー項目1の制限文字数\'');
            }
            
            // freeitem2_max_lengthカラムが存在しない場合のみ追加
            if (!in_array('freeitem2_max_length', $columnNames)) {
                // freeitem2_max_lengthカラムを追加
                $this->addSql('ALTER TABLE dtb_school ADD freeitem2_max_length INT UNSIGNED DEFAULT NULL COMMENT \'フリー項目2の制限文字数\'');
            }
        }
    
        public function down(Schema $schema): void
        {
            $schemaManager = $this->connection->createSchemaManager();
            
            // テーブルが存在するかチェック
            if (!$schemaManager->tablesExist(['dtb_school'])) {
                return;
            }
            
            $columns = $schemaManager->listTableColumns('dtb_school');
            $columnNames = array_map(function($column) {
                return $column->getName();
            }, $columns);
            
            // freeitem1_max_lengthカラムが存在する場合のみ削除
            if (in_array('freeitem1_max_length', $columnNames)) {
                // ロールバック時にカラムを削除
                $this->addSql('ALTER TABLE dtb_school DROP COLUMN freeitem1_max_length');
            }
            
            // freeitem2_max_lengthカラムが存在する場合のみ削除
            if (in_array('freeitem2_max_length', $columnNames)) {
                $this->addSql('ALTER TABLE dtb_school DROP COLUMN freeitem2_max_length');
            }
        }
    }