如何使一个varchar空和唯一的一起在mysql (laravel)


how to make a varchar nullable and unique together in mysql (laravel)

我可以使MySQL列可空且唯一吗?我有一个表,存储用户Email_id,如果用户想提供,否则它将是(null)。我在其他一些问题中读到,我可以用默认NULL创建一个唯一的字段。但是在创建表

时出现了这个错误
#1067 - Invalid default value for 'email' (i make it only for test purpose)

使用larave模式构建器类

生成主表
$table->text('email')->nullable()->unique(); (no default added)
在DB

+--------------+------------------+------+-----+---------+----------------+
| Field        | Type             | Null | Key | Default | Extra          |
+--------------+------------------+------+-----+---------+----------------+ 
| email_id     | varchar(200)     | YES  | UNI | NULL    |                |

现在错误是

Duplicate entry '' for key 'users_email_id_unique' (when inserting email with empty string) 

现在的问题是如何处理一个唯一的和可空的varchar字段。

我知道这是一个老问题,这是给其他有同样问题的人的。

你想添加一个字符串。你让列 nullable 。这意味着你正在尝试一些你不应该做的事情。可以发送多个null值,但不能发送多个empty string。MySQL考虑作为值

或者你可以在你的模态

中写一个mutator
public function setEmailAttribute($value) {
    if ( empty($value) ) { // will check for empty string
    $this->attributes['email'] = NULL;
    } else {
        $this->attributes['email'] = $value;
    }
}

当必须插入null时,我们犯了一个错误。在null的情况下,我们必须像这样声明null:

if(empty($request->email_id)){
    $user->email_id = NULL;
}

不要使用"NULL",这将被视为字符串。

您可以在Laravel迁移中使用$table->string('mobile')->nullable()->unique();