如何在 mysql (laravel) 中使 varchar 可以为空且唯一

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17241586/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:00:43  来源:igfitidea点击:

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

phpmysqlschemalaravel

提问by Natwar Singh

Can i make a MySQL column nullable and unique together. I have a table that store users Email_id if user wants to provide else it will be (null). I read in some other questions that i can make a unique field with default NULL. but i get this error when creating table

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

#1067 - Invalid default value for 'email' (i make it only for test purpose)

the main table is generated with larave schema builder class

主表是用 laave 模式构建器类生成的

$table->text('email')->nullable()->unique(); (no default added)

in DB

在数据库中

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

now error is

现在错误是

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

Now question is how to handle a varchar field which is unique and nullable together.

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

回答by Dasun

I know this is an old question, this is for others who have the same issue.

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

You are trying to add an emptystring. You made column nullableand unique. That means you are trying something you shouldn't. You can send multiple nullvalues but not mutiple emptystring. MySQL consider emptyas a value.

您正在尝试添加一个字符串。您将列设为 nullableunique。这意味着您正在尝试不应该做的事情。您可以发送多个值,但不能发送多个字符串。MySQL 将视为一个值。

or you could write a mutatorin your modal

或者你可以在你的模态中写一个mutator

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

回答by Natwar Singh

I am not able to do like that. so i use some other technique. I make a new field have_emailmake default 0and if user provide Email Id i put 1in this field.

我不能那样做。所以我使用其他一些技术。我将一个新字段have_email设为默认值0,如果用户提供电子邮件 ID,我将1放在此字段中。

And if your not provide email id have_emailalready 0and to make emailfield unique just put your ID ( primary key ).

如果你不提供电子邮件IDhave_email已经0并作出email领域独树一帜只是把你的ID(主键)。