在laravel迁移中使用UUID作为默认值

时间:2019-02-25 12:42:40

标签: laravel-migrations

我进行了以下迁移:

<?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时,我看到以下内容:

enter image description here

怎么了?

2 个答案:

答案 0 :(得分:1)

当我遇到相同问题时遇到此问题: 使用MySQL 8,您可以 将函数用作默认值。但是您需要在它们周围放上括号。如此有效:

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

但这与MySQL 5.7不兼容!

答案 1 :(得分:0)

您不能将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');
        });
    }
}