You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中如何通过迁移为所有数据表批量添加指定公共字段?

Laravel 8 批量为所有数据表添加统一字段解决方案

前置依赖安装

由于需要读取数据库表列表,需先安装兼容PHP 7.3的doctrine/dbal扩展,执行命令:
composer require doctrine/dbal:^2.13

注意不要安装3.x以上版本,否则会和PHP 7.3、Laravel 8产生兼容冲突

步骤1:生成迁移文件

执行Artisan命令生成迁移文件:
php artisan make:migration add_data_owner_company_id_to_all_tables
打开生成的迁移文件,替换为以下代码:

<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // 配置不需要添加字段的排除表,可根据实际业务调整
        $excludeTables = [
            'migrations',
            'failed_jobs',
            'sessions',
            'cache',
            'password_resets',
            'personal_access_tokens'
        ];

        // 获取当前数据库所有表名
        $tables = Schema::getConnection()
            ->getDoctrineSchemaManager()
            ->listTableNames();

        foreach ($tables as $tableName) {
            if (in_array($tableName, $excludeTables)) {
                continue;
            }

            Schema::table($tableName, function (Blueprint $table) {
                // 可根据业务需求调整字段属性,示例为无符号、可空、放在id字段后、添加普通索引
                $table->unsignedInteger('data_owner_company_id')
                    ->nullable()
                    ->after('id')
                    ->index();
            });
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        $excludeTables = [
            'migrations',
            'failed_jobs',
            'sessions',
            'cache',
            'password_resets',
            'personal_access_tokens'
        ];

        $tables = Schema::getConnection()
            ->getDoctrineSchemaManager()
            ->listTableNames();

        foreach ($tables as $tableName) {
            if (in_array($tableName, $excludeTables)) {
                continue;
            }

            Schema::table($tableName, function (Blueprint $table) {
                $table->dropColumn('data_owner_company_id');
            });
        }
    }
};

步骤2:调整配置

  • 根据自身业务需求调整$excludeTables数组,过滤不需要添加字段的表
  • 调整data_owner_company_id字段的属性,若需要非空约束建议先设为可空,待历史数据补全后再单独修改字段属性

步骤3:执行迁移

测试环境验证无误后,执行命令完成批量字段添加:
php artisan migrate
如果需要回滚操作,执行以下命令即可批量删除所有表的该字段:
php artisan migrate:rollback

注意事项

  • 若单表数据量超过百万,建议在业务低峰期执行操作,避免锁表影响正常业务
  • 生产环境执行前务必做好数据库备份

内容的提问来源于stack exchange,提问作者Skywarth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 13:45:04