• Час читання ~2 хв
  • 15.06.2023

Однією з поширених проблем при міграції застарілої програми PHP на Laravel є створення міграції бази даних на основі існуючої бази даних.

Залежно від розміру бази даних, це може стати виснажливим завданням. Мені доводилося робити це кілька разів, але нещодавно я натрапив на базу даних з більш ніж сотнею таблиць.

Як програміст, у нас немає терпіння виконувати таке завдання, і ми не повинні. Перша думка - як це автоматизувати. Маючи це на увазі, я шукав існуюче рішення, знайшов кілька пакетів і вибрав один за kitloong, пакет генератора міграції Laravel.

Практичний приклад використання існуючої структури

бази даних Створення таблиць

CREATE TABLE permissions
(
    id bigint unsigned auto_increment primary key,
    name varchar(255) not null,
    guard_name varchar(255) not null,
    created_at timestamp    null,
    updated_at timestamp    null,
    constraint permissions_name_guard_name_unique
    unique (name, guard_name)
)
collate = utf8_unicode_ci;
CREATE TABLE roles
(
    id bigint unsigned auto_increment primary key,
    team_id bigint unsigned null,
    name varchar(255) not null,
    guard_name varchar(255) not null,
    created_at timestamp null,
    updated_at timestamp null,
    constraint roles_team_id_name_guard_name_unique
    unique (team_id, name, guard_name)
)
collate = utf8_unicode_ci;
CREATE TABLE role_has_permissions
(
    permission_id bigint unsigned not null,
    role_id bigint unsigned not null,
    primary key (permission_id, role_id),
    constraint role_has_permissions_permission_id_foreign
    foreign key (permission_id) references permissions (id)
    on delete cascade,
    constraint role_has_permissions_role_id_foreign
    foreign key (role_id) references roles (id)
    on delete cascade
)
collate = utf8_unicode_ci;
CREATE INDEX roles_team_foreign_key_index on roles (team_id);

Встановлення пакета Запуск команди пакета

composer require --dev kitloong/laravel-migrations-generator

, яка виконує магію Ви

можете вказати або ігнорувати таблиці, які ви хочете використовувати--tables=, або --ignore= відповідно.

Нижче наведено команду, яку я запустив для таблиць, які ми створили вище. Щоб працювати для всіх таблиць, не додавайте жодних додаткових фільтрів.

php artisan migrate:generate --tables="roles,permissions,role_permissions"

Виведення

Using connection: mysql
Generating migrations for: permissions,role_has_permissions,roles
Do you want to log these migrations in the migrations table? (yes/no) [yes]:
> yes
Setting up Tables and Index migrations.
Created: /var/www/html/database/migrations/2023_06_08_132125_create_permissions_table.php
Created: /var/www/html/database/migrations/2023_06_08_132125_create_role_has_permissions_table.php
Created: /var/www/html/database/migrations/2023_06_08_132125_create_roles_table.php
Setting up Views migrations.
Setting up Stored Procedures migrations.
Setting up Foreign Key migrations.
Created: /var/www/html/database/migrations/2023_06_08_132128_add_foreign_keys_to_role_has_permissions_table.php
Finished!

команд Перевірка файлів

міграції Таблиця дозволів: Таблиця "Ролі": Зведена таблиця: Додайте зовнішній ключ до зведеної таблиці: 2023_06_08_132125_create_roles_table.php

...
Schema::create('roles', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->unsignedBigInteger('team_id')
        ->nullable()
        ->index('roles_team_foreign_key_index');
    $table->string('name');
    $table->string('guard_name');
    $table->timestamps();
    $table->unique(['team_id', 'name', 'guard_name']);
});
...

...
Schema::create('roles', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->unsignedBigInteger('team_id')
        ->nullable()
        ->index('roles_team_foreign_key_index');
    $table->string('name');
    $table->string('guard_name');
    $table->timestamps();
    $table->unique(['team_id', 'name', 'guard_name']);
});
...

2023_06_08_132125_create_permissions_table.php

...
Schema::create('role_has_permissions', function (Blueprint $table) {
    $table->unsignedBigInteger('permission_id');
    $table->unsignedBigInteger('role_id')
        ->index('role_has_permissions_role_id_foreign');
    $table->primary(['permission_id', 'role_id']);
});
...

...
Schema::table('role_has_permissions', function (Blueprint $table) {
    $table->foreign(['permission_id'])
        ->references(['id'])
        ->on('permissions')
        ->onUpdate('NO ACTION')
        ->onDelete('CASCADE');
    $table->foreign(['role_id'])
        ->references(['id'])
        ->on('roles')
        ->onUpdate('NO ACTION')
        ->onDelete('CASCADE');
});
...

2023_06_08_132125_create_role_has_permissions_table.php2023_06_08_132128_add_foreign_keys_to_role_has_permissions_table.phpЦе лише одна з проблем при міграції застарілої програми PHP до Laravel.

Наступний пост буде про несумісність алгоритму хешування паролів.

Приєднуйтесь до обговорення в Twitter.

Comments

No comments yet
Yurij Finiv

Yurij Finiv

Full stack

Про мене

Professional Fullstack Developer with extensive experience in website and desktop application development. Proficient in a wide range of tools and technologies, including Bootstrap, Tailwind, HTML5, CSS3, PUG, JavaScript, Alpine.js, jQuery, PHP, MODX, and Node.js. Skilled in website development using Symfony, MODX, and Laravel. Experience: Contributed to the development and translation of MODX3 i...

Про автора CrazyBoy49z
WORK EXPERIENCE
Контакти
Ukraine, Lutsk
+380979856297