Laravel 在每个 table 中迁移回填 uuid

Laravel migration to backfill uuids in every table

我正在尝试创建一个数据库迁移 (MySQL) 以回填所有 table 中的 uuid(大约 80 table 秒,一些有 130k+ 行)。要直接在 MySQL 中执行此操作,我可以通过 table 和 运行:

进入 table
UPDATE <TABLE_NAME> SET uuid = (SELECT md5(UUID()))';

它确实为每行添加了一个唯一的 UUID。如果我循环遍历所有 tables 和 运行 每个 table:

的 DB facade 语句
class BackfillUuidsIntoAllTables extends Migration
{
    protected $dbName;
    protected $tables;

    public function __construct()
    {
        $this->dbName = config('database.connections.' . config('database.default') . '.database');
        $this->tables = DB::select('SHOW TABLES');
    }

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        foreach ($this->tables as $table) {
            Schema::table($table->{'Tables_in_' . $this->dbName}, function ($table) {
                $tableName = $table->getTable();

                DB::statement("UPDATE $tableName SET uuid = (SELECT md5(UUID()))");
        }
    }
}

它执行速度很快,但对整个 table 使用相同的 uuid。我是不是为了 运行 而遗漏了一些东西,所以每一行实际上都有一个唯一的 uuid?

如果您将行的唯一 ID 添加到 md5() 调用,它应该为每行生成一个不同的字符串。此外,嵌套的 SELECT 似乎没有必要。

这样就可以了:

UPDATE
    <tablename>
SET
    `uuid` = MD5(CONCAT(UUID(), `id`))