マイグレーション作成方法
・コマンドで作成する
php app/console migrations:generate
・phpファイルを手動で作成する
次のファイルを src/Eccube/Resource/doctrine/migration/Version20180412171816.php の場所に作成します。
<?php
namespace DoctrineMigrations;
use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;
/**
* Auto-generated Migration: Please modify to your needs!
*/
class Version20180412171816 extends AbstractMigration
{
/**
* @param Schema $schema
*/
public function up(Schema $schema)
{
// this up() migration is auto-generated, please modify it to your needs
}
/**
* @param Schema $schema
*/
public function down(Schema $schema)
{
// this down() migration is auto-generated, please modify it to your needs
}
}
upメソッドの中にマイグレーションが実行された時に実行したい内容をSQL等で指定します。
downメソッドの中にマイグレーションが巻き戻された時に実行したい内容をSQL等で指定します。
例えばupメソッドは下記のようになります。
・SQL文を実行する例(おすすめ商品を登録)
/**
* @param Schema $schema
*/
public function up(Schema $schema)
{
// this up() migration is auto-generated, please modify it to your needs
if (!$schema->hasTable(self::NAME)) {
return true;
}
$this->addSql("DELETE FROM plg_recommend_product");
$this->addSql("INSERT INTO plg_recommend_product (recommend_product_id, comment, rank, del_flg, create_date, update_date, product_id) VALUES (1, 'おすすめ商品情報', 1, 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, 1)");
$this->addSql("INSERT INTO plg_recommend_product (recommend_product_id, comment, rank, del_flg, create_date, update_date, product_id) VALUES (2, 'おすすめ商品情報', 2, 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, 2)");
}
・Entityを使用する例(ページの名前を変更)
/**
* @param Schema $schema
*/
public function up(Schema $schema)
{
// this up() migration is auto-generated, please modify it to your need
$app = Application::getInstance();
$PageLayout = $app['eccube.repository.page_layout']->find(35);
if ($PageLayout) {
$PageLayout->setName('お買い物ガイド');
}
$app['orm.em']->flush();
}
マイグレーションの実行・巻き戻し
作成したマイグレーションを実行するには実行コマンドを打ちます。
upメソッドの内容が実行され、マイグレーションの実行が記録されます。
実行していないマイグレーションをすべて実行するには、
php app/console migrations:migrate
ファイルを指定して実行するには
php app/console migrations:execute 20180412171816 –up
ちなみにマイグレーションを巻き戻すには
php app/console migrations:execute 20180412171816 –down
この場合downメソッドの内容が実行され、マイグレーション「20180412171816」は未実行の状態になります。
マイグレーションファイルを使用するメリットは
マイグレーションによりデータベースの内容を変更することで、環境間のデータの差異をなくすことができます。
開発環境とステージング環境で設定を揃えたい時、ブロックの配置を何度も行いたくない場合に有効です。
Gitに登録して環境を揃えられるのでチーム開発では必須です。
EC-CUBEに関するお問い合わせ
[重要]現在公式にセキュリティサポートが切れていないPHPは8.1以上、MySQLは8.0以上で、対応しているEC-CUBEバージョンは4.2以上です。古いEC-CUBEを使っている方は適切なタイミングでバージョンアップをご検討ください。
EC-CUBEゴールドパートナー