1

I have 88 tables in the database and I need one new column in each the table one single solution is I make a migration and write 88 functions for all tables to add the new column as well as 88 to remove that column.

enter image description here

Is there any way to get all the table names in 1 variable and then by using foreach add a new column by a single piece of code?

  1. get all table name in variable

  2. by foreach loop add new column to that particular variable

$allTables=?
foreach($allTables as $singleTable){
    add new column
}

But HOW? I want to add team_id in all the tables but I need an optimal solution.

I am using laravel 5.4 version.

4

2 回答 2

2

试试下面的。

// Get the default database name
$dbName = config('database.connections.' . config('database.default') . '.database');

$tables = DB::select('SHOW TABLES');

foreach($tables as $table)
{
    Schema::table($table->{'Tables_in_' . $dbName}, function($table) {
        // Add the column
        $table->string('some_column');
    });
}

要了解发生了什么,请分析 $tables 变量,但应该非常简单。

于 2017-07-18T06:11:52.017 回答
1

我已经尝试过了,它也可以工作,但你的解决方案比这更好,@Artur。

class AddTeamIdToNecessaryTables extends Migration
{
    protected $table_names;

    function __construct()
    {
        $this->table_names = [
            'accounts', 'suppliers', 'expenses', 'draft_invoices', 'quote_jobs',
            'committed_invoices', 'quotes', 'rate_plans', 'call_categories',
            'prefix_groups', 'draft_items', 'committed_invoice_cdrs', 'committed_items',
            'call_data_records', 'committed_temp_xero_infos', 'did_records',
            'prefixes', 'prefix_cost_prices', 'purchase_items', 'purchase_orders',
            'quote_costs', 'sippy_root_accounts', 'temp_xero_infos', 'sippy_infos', 'committed_jobs'
        ];
    }

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        \DB::beginTransaction();
        try {
            foreach ($this->table_names as $table_name) {
                Schema::table($table_name, function (Blueprint $table) {
                    $table->integer('team_id')->unsigned()->nullable()->after('id');
                    $table->foreign('team_id')->references('id')->on('teams');
                });
            }
            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollback();
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        \DB::beginTransaction();
        try {
            foreach ($this->table_names as $table_name){
                Schema::table($table_name, function (Blueprint $table) {
                    $table->dropForeign(['team_id']);
                    $table->dropColumn('team_id');
                });
            }
            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollback();
        }
    }
}
于 2017-07-18T06:52:15.277 回答