migrations/Version20230301094717.php line 1

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace DoctrineMigrations;
  4. use App\Entity\Role;
  5. use Doctrine\DBAL\Schema\Schema;
  6. use Doctrine\Migrations\AbstractMigration;
  7. /**
  8.  * Auto-generated Migration: Please modify to your needs!
  9.  */
  10. final class Version20230301094717 extends AbstractMigration {
  11.     public function getDescription(): string {
  12.         return '';
  13.     }
  14.     public function up(Schema $schema): void {
  15.         // Delete ON DELETE CASCADE
  16.         $this->addSql("ALTER TABLE user_role DROP FOREIGN KEY FK_2DE8C6A3D60322AC");
  17.         $this->addSql("
  18.             ALTER TABLE user_role
  19.             ADD CONSTRAINT FK_2DE8C6A3D60322AC
  20.                 FOREIGN KEY (role_id) REFERENCES role (id)
  21.                     ON UPDATE CASCADE");
  22.         // Add ROLE_DIPLOME if not exist and get ID
  23.         $roleId $this->connection->executeQuery(
  24.             'SELECT r.id as id
  25.                 FROM role r
  26.                 WHERE r.role = ?',
  27.             [Role::ROLE_DIPLOME])
  28.             ->fetchOne();
  29.         if (!$roleId) {
  30.             $addRole $this->connection->prepare(
  31.                 'INSERT INTO role (role) VALUES (:roleName)'
  32.             );
  33.             $addRole->bindValue('roleName'Role::ROLE_DIPLOME);
  34.             $addRole->executeStatement();
  35.             $roleId $this->connection->lastInsertId();
  36.         } else {
  37.             $roleId $roleId;
  38.         }
  39.         // Add ROLE_DIPLOME to person_degree not having this role
  40.         $user_ids $this->connection->executeQuery(
  41.             'SELECT u.id as id
  42.                 FROM person_degree p, user u
  43.                 WHERE p.user_id = u.id'
  44.         )->fetchAllAssociative();
  45.         foreach ($user_ids as $user_id) {
  46.             $this->addSql('INSERT INTO user_role (user_id, role_id)
  47.                     SELECT ?, ?
  48.                     WHERE NOT EXISTS (
  49.                         SELECT 1 FROM user_role ur
  50.                         WHERE ur.user_id = ? AND ur.role_id = ?
  51.                     )', [$user_id['id'], $roleId$user_id['id'], $roleId]);
  52.         }
  53.     }
  54.     public function down(Schema $schema): void {
  55.         // this down() migration is auto-generated, please modify it to your needs
  56.         $this->addSql('ALTER TABLE user_role DROP FOREIGN KEY FK_2DE8C6A3D60322AC');
  57.         $this->addSql('ALTER TABLE user_role ADD CONSTRAINT FK_2DE8C6A3D60322AC FOREIGN KEY (role_id) REFERENCES role (id)');
  58.     }
  59. }