php - Laravel 迁移唯一仍然允许相同的条目
问题描述
我有一个表迁移,我尝试强制将 phone_number 字段验证为唯一:
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('phone_number');
$table->string('email')->nullable();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->string('user_type')->nullable();
$table->boolean('is_admin');
$table->rememberToken();
$table->timestamps();
$table->unique('phone_number');
});
但是,当我尝试使用相同的电话号码(例如“27841231234”)创建两个用户时,它仍然允许它,并且只是为它们分配了两个不同的 ID……我是否错误地理解了独特的功能?以及如何强制 laravel 不允许存储两个相似的电话号码?
编辑:
这是我的 MYSQL 数据库结构,它还表明该字段是唯一的,但仍允许重复值:
| Field | Type | Null | Key | Default | Extra |
+-------------------+---------------------+------+-----+---------+----------------+
| id | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
| phone_number | varchar(255) | NO | UNI | NULL | |
| email | varchar(255) | YES | | NULL | |
| email_verified_at | timestamp | YES | | NULL | |
| password | varchar(255) | NO | | NULL | |
| user_type | varchar(255) | YES | | NULL | |
| is_admin | tinyint(1) | NO | | NULL | |
| remember_token | varchar(100) | YES | | NULL | |
| created_at | timestamp | YES | | NULL | |
| updated_at | timestamp | YES | | NULL | |
+-------------------+---------------------+------+-----+---------+----------------+
解决方案
试试这个:
- $table->string('phone_number')->unique();
而不是这两个:
- $table->string('phone_number');
- $table->unique('phone_number');
最后运行这个命令:
- php工匠迁移
希望你能得到你想要的结果。
推荐阅读
- android - JobIntentService 作业 ID 是全局唯一的还是由类限定?
- postgresql - 无法在命令行上运行 psql...在 macOS Mojave 上安装了 PostgreSQL.app
- c# - 通过 C# 调用 powershell 脚本并将输出捕获到 ASP
- javascript - 尝试创建一个将更改字体系列的按钮
- odata - 在 .Net Core 3.1 OData EDMModelBuilder 中公开私有设置器
- c++ - 尝试使用 CreateFileMapping 和自定义 DACL 创建只读共享内存区域在 OpenFileMapping 中失败
- laravel - 更改 Laravel Web Tinker 公共文件目录 - 防止保存时出现 403 错误
- powerbi - 如何使用 PowerBI DAX 瀑布图计算方差
- python - 收到此错误 InvalidArgumentError: Default MaxPoolingOp only support NHWC on device type CPU [[node sequences_5/max_pooling2d_5/MaxPool
- git - 如何在 GitHub 上保留最新版本的二进制文件而不完全跟踪它们?