[英]Drop Unique Index Laravel 5
我在运行php artisan migrate
时一直得到这个
SQLSTATE[42000]:语法错误或访问冲突:1091 无法删除“电子邮件”; 检查列/键是否存在
虽然我看到我的数据库中存在电子邮件。
我的迁移脚本。 我试图删除唯一约束。
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AlterGuestsTable3 extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('guests', function(Blueprint $table)
{
$table->dropUnique('email');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('guests', function(Blueprint $table)
{
$table->dropUnique('email');
});
}
}
我忘记清除任何缓存了吗?
对我有什么提示吗?
通过官方文档可以看到以下内容:
如果将列数组传递给删除索引的方法,则将根据表名、列和键类型生成常规索引名称:
Schema::table('geo', function ($table) { $table->dropIndex(['state']); // Drops index 'geo_state_index' });
您只需在字段名称周围使用[]
即可删除它:
Schema::table('guests', function(Blueprint $table)
{
$table->dropUnique(['email']);
});
当删除索引时,Laravel 会期望给出索引的全名。
您可以检查您的数据库以获取索引的全名,但如果密钥是由先前的 Laravel 迁移生成的,则其名称应符合单一、简单的命名约定。
以下是文档对其命名约定的说明(从 v5.2 开始):
默认情况下,Laravel 会自动为索引分配一个合理的名称。 只需连接表名、索引列的名称和索引类型。
我的猜测是这就是您收到错误的原因。 没有email
索引,但可能有一个guests_email_unique
索引。
试一试这个迁移:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AlterGuestsTable3 extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('guests', function(Blueprint $table)
{
$table->dropUnique('guests_email_unique');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('guests', function(Blueprint $table)
{
//Put the index back when the migration is rolled back
$table->unique('email');
});
}
}
我知道创建索引时指定列名有点令人困惑,但稍后删除索引时需要提供索引的全名。
请注意,我也调整了down()
方法,以便它通过添加回来来恢复删除唯一索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.