<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Exception;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20230220121817 extends AbstractMigration
{
public function up(Schema $schema): void
{
$this->addSql('CREATE TABLE service_campaign_message (id INT AUTO_INCREMENT NOT NULL, message_id INT NOT NULL, service_campaign_id INT NOT NULL, created_at DATETIME NOT NULL COMMENT \'(DC2Type:datetime_immutable)\', updated_at DATETIME NOT NULL COMMENT \'(DC2Type:datetime_immutable)\', deleted_at DATETIME DEFAULT NULL COMMENT \'(DC2Type:datetime_immutable)\', UNIQUE INDEX UNIQ_B9428B42537A1329 (message_id), INDEX IDX_B9428B423AA3D1D8 (service_campaign_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB');
$this->addSql('ALTER TABLE service_campaign_message ADD CONSTRAINT FK_B9428B42537A1329 FOREIGN KEY (message_id) REFERENCES message (id)');
$this->addSql('ALTER TABLE service_campaign_message ADD CONSTRAINT FK_B9428B423AA3D1D8 FOREIGN KEY (service_campaign_id) REFERENCES service_campaign (id)');
$serviceCampaigns = $this->getData('SELECT id, message_id FROM service_campaign');
foreach ($serviceCampaigns as $serviceCampaign) {
$now = new \DateTimeImmutable();
$this->addSql('INSERT INTO service_campaign_message (message_id, service_campaign_id, created_at, updated_at) VALUES (?,?,?,?)', [
$serviceCampaign['message_id'],
$serviceCampaign['id'],
$now->format('Y-m-d H:i:s'),
$now->format('Y-m-d H:i:s'),
]);
}
$this->addSql('ALTER TABLE service_campaign DROP FOREIGN KEY FK_B176F1DD537A1329');
$this->addSql('ALTER TABLE service_campaign DROP message_id');
}
public function down(Schema $schema): void
{
$serviceCampaignMessages = $this->getData('SELECT message_id, service_campaign_id FROM service_campaign_message');
$this->addSql('ALTER TABLE service_campaign_message DROP FOREIGN KEY FK_B9428B42537A1329');
$this->addSql('ALTER TABLE service_campaign_message DROP FOREIGN KEY FK_B9428B423AA3D1D8');
$this->addSql('DROP TABLE service_campaign_message');
$this->addSql('ALTER TABLE service_campaign ADD message_id INT NOT NULL');
foreach ($serviceCampaignMessages as $serviceCampaignMessage) {
$this->addSql(
'UPDATE service_campaign SET message_id = :messageId WHERE id = :serviceCampaignId',
[
'messageId' => $serviceCampaignMessage['message_id'],
'serviceCampaignId' => $serviceCampaignMessage['service_campaign_id'],
]
);
}
}
/**
* @throws Exception
*/
private function getData(string $sql): \Traversable
{
return $this->connection->executeQuery($sql)->iterateAssociative();
}
}