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

Laravel migrations 在laravel迁移中使用UUID作为默认值,laravel-migrations,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. *

我有以下迁移:

<?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');
        });
    }
}

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

当我遇到同样的问题时:
使用MySQL 8,您可以使用函数作为默认值。但你需要把偏执放在他们周围。所以这是可行的:

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

但这将与MySQL 5.7不兼容

UUID()是MySQL中的触发器吗?我记得。UUID()是mysql中的默认函数。例如,请参见此处,请求
SELECT UUID()
为我提供了UUID。为什么?例如,我可以使用
NOW()。这就是工作。我已将代码更新为默认值(DB::raw('NOW()')并且工作得很好。我可以在我的数据库中看到默认的日期时间值。现在()这可能是一个例外,但请看这里。对不起,我不明白。我还没有为
NOW()
编写触发器,它可以工作。
NOW()
UUID()
之间的区别是什么。两者都是功能,对吗?从您的链接中,我了解到我需要为调用
UUID()
设置触发器。那么为什么我不必为
NOW()
这样做呢?通常它不应该工作
,除了一个例外,default子句中指定的默认值必须是一个文本常量;它不能是函数或表达式。例如,这意味着您不能将日期列的默认值设置为函数(如NOW()或CURRENT_date)的值对于您的问题,触发器或预查询应该可以解决它。