首页 > 解决方案 > 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    |                |
+-------------------+---------------------+------+-----+---------+----------------+

标签: phplaravel

解决方案


试试这个:

  • $table->string('phone_number')->unique();

而不是这两个:

  • $table->string('phone_number');
  • $table->unique('phone_number');

最后运行这个命令:

  • php工匠迁移

希望你能得到你想要的结果。


推荐阅读