【问题标题】:Using UUID as default value in a laravel migration在 laravel 迁移中使用 UUID 作为默认值
【发布时间】:2026-01-23 00:45:01
【问题描述】:

我有以下迁移:

<?php

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

class UpdateRatingGameUserAnswersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('rating_games_user_answers', function (Blueprint $table) {
            $table->uuid('answer_token')->default(DB::raw('UUID()'));
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('rating_games_user_answers', function (Blueprint $table) {
            $table->dropColumn('answer_token');
        });
    }
}

如您所见,我正在尝试将 UUID 设置为默认值。我看过here

但是当我运行php artisan migrate 时,我看到以下内容:

怎么了?

【问题讨论】:

标签: laravel-migrations


【解决方案1】:

当我遇到同样的问题时遇到了这个问题: 在 MySQL 8 中,您可以使用函数作为默认值。但是你需要在它们周围加上括号。所以这行得通:

$table->uuid('uid')->default(DB::raw('(UUID())'));

但这与 MySQL 5.7 不兼容!

【讨论】:

  • 你是个圣人。谢谢。
【解决方案2】:

你不能使用 mySQL 函数作为默认值,要么设置它,要么使用触发器。

请像这样尝试:

<?php

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

class UpdateRatingGameUserAnswersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('rating_games_user_answers', function (Blueprint $table) {
            $uuid = DB::raw('select UUID()');
            $table->uuid('answer_token')->default($uuid);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('rating_games_user_answers', function (Blueprint $table) {
            $table->dropColumn('answer_token');
        });
    }
}

【讨论】:

  • 为什么?例如,我可以使用NOW()。这是工作。我已将代码更新为$table-&gt;dateTime('answer_token')-&gt;default(DB::raw('NOW()'));,效果很好。我可以在我的数据库中看到默认的 dateTime 值。
  • NOW() 这可能是一个例外,但请参阅此处forums.mysql.com/read.php?10,91149,91161#msg-91161
  • 对不起,我不明白。我还没有为NOW() 编写触发器,它可以工作。 NOW()UUID() 之间的区别。两者都是函数,对吧?从您的链接中,我了解到我需要触发呼叫UUID()。那么为什么我不必为NOW() 这样做呢?
  • 通常它不应该工作 With one exception, the default value specified in a DEFAULT clause must be a literal constant; it cannot be a function or an expression. This means, for example, that you cannot set the default for a date column to be the value of a function such as NOW() or CURRENT_DATE. dev.mysql.com/doc/refman/5.7/en/data-type-defaults.html 至于你的问题触发器或预查询应该解决它。