Migration in several tables with the same prefix

Asked

Viewed 173 times

1

Is it possible with the Laravel to generate a migration that changes several tables with the same prefix? for example: in the tables pesquisas_187 and pesquisas_146 (tables that have the same fields)

Schema::table('pesquisas_', function (Blueprint $table) {
   $table->string('code')->after('name');
});

1 answer

1


There’s nothing ready in the for that purpose, but nothing prevents the coding of a Migration with the following code:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class Padrao1 extends Migration
{
    public function up()
    {
        $sql = 'SELECT TABLE_NAME as name FROM information_schema.tables ';
        $sql .= 'where TABLE_SCHEMA=? and TABLE_NAME LIKE ? ';
        $result = DB::select($sql, [getenv('DB_DATABASE'), 'pesquisas_%']);
        foreach($result as $table)
        {
            Schema::table($table->name, function (Blueprint $table) {
                $table->string('code')->after('name');
            });
        }
    }

    public function down()
    {

    }
}

In this code is done a search on the tables of the database configured in the file .env with the key DB_DATABASE (getenv('DB_DATABASE')) with a filter over the prefix tables pesquisas_, and its return is a list of all tables belonging to this prefix, the rest is equal using Schema::table, as demonstrated in the code.

References:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.