我在使用MS Sql Server 2014时使用Laravel 5。 我想创建一个唯一约束,但它应该允许多个空值。
以下是我正在使用的代码。其中' passport_no'如果不是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');
});
答案 0 :(得分:0)
您可以使用唯一的索引并在其过滤器中设置您的条件,如
passport_no is not null
通过这种方式你可以解决你的问题
答案 1 :(得分:0)
这是一个古老的问题,但是窗台需要回答。如上所述,2008年起的SQL Server(包括Azure SQL)支持可以解决的特殊索引。在数据库迁移中,您可以检查使用的驱动程序,并用特定于MSSQL的语句替换数据库构建器标准SQL。
此迁移示例适用于Laravel 5+,并创建了一个具有唯一但可为空的api_token
列的users表:
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');
}
}