Laravel Eloquent 如何创建具有重复 NULL 的 UNIQUE 约束 [英] Laravel Eloquent how to create UNIQUE constraint with duplicate NULLs

查看:34
本文介绍了Laravel Eloquent 如何创建具有重复 NULL 的 UNIQUE 约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是带有 MS Sql Server 2014 的 Laravel 5.我想创建一个唯一约束,但它应该允许多个空值.

I'm usinq Laravel 5 with MS Sql Server 2014. I want to create a unique constraint but it should allow multiple null values.

这是我正在使用的代码.如果 'passport_no' 不为空,则必须是唯一的.

Here is code I'm using. Where 'passport_no' has to be unique if not null.

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

推荐答案

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

This is an ancient question, but sill needs answering. As stated above, SQL Server from 2008, including Azure SQL, supports a special index that will work around it. In your database migration you can check the driver used and substitute the database builder standard SQL with an MSSQL-specific statement.

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

This migration example is for Laravel 5+, and creates a users table with a unique, but nullable, api_token column:

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

这篇关于Laravel Eloquent 如何创建具有重复 NULL 的 UNIQUE 约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆