Laravel Eloquent 如何使用重复的 NULL 创建 UNIQUE 约束

leo*_*oel 5 sql-server eloquent laravel-5

我将 Laravel 5 与 MS Sql Server 2014 一起使用。我想创建一个唯一约束,但它应该允许多个空值。

这是我正在使用的代码。其中“passport_no”如果不为空,则必须是唯一的。

Schema::create('UserProfile', function(Blueprint $table){
    $table->increments('userprofile_id');
    $table->integer('user_id')->unsigned();
    $table->string('passport_no', 50)->unique()->nullable();

    $table->foreign('user_id')->references('id')->on('users')
            ->onUpdate('cascade')->onDelete('cascade');
});
Run Code Online (Sandbox Code Playgroud)

Jas*_*son 6

这是一个古老的问题,但仍然需要回答。如上所述,从 2008 年开始的 SQL Server(包括 Azure SQL)支持可以解决该问题的特殊索引。在数据库迁移中,您可以检查所使用的驱动程序,并用特定于 MSSQL 的语句替换数据库构建器标准 SQL。

此迁移示例适用于 Laravel 5+,并创建一个具有唯一但可为空的api_token列的用户表:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->timestamps();

        $table->string('name', 100)->nullable()->default(null);
        // etc.

        $table->string('api_token', 80)->nullable()->default(null);

        if (DB::getDriverName() !== 'sqlsrv') {
            $table->unique('api_token', 'users_api_token_unique');
        }
    });

    if (DB::getDriverName() === 'sqlsrv') {
        DB::statement('CREATE UNIQUE INDEX users_api_token_unique'
           . ' ON users (api_token)'
           . ' WHERE api_token IS NOT NULL');
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 -1

您可以使用唯一索引并在其过滤器中设置您的条件,例如

passport_no is not null
Run Code Online (Sandbox Code Playgroud)

这样你就可以解决你的问题