Php 在Laravel 5.4中从迁移中删除列
我使用迁移创建了一个表,如下所示:Php 在Laravel 5.4中从迁移中删除列,php,laravel,migration,Php,Laravel,Migration,我使用迁移创建了一个表,如下所示: Schema::create('listings', function (Blueprint $table) { $table->increments('id'); $table->decimal('original_price', 10, 2); $table->decimal('discouted_price', 10, 2); $table->integer('c
Schema::create('listings', function (Blueprint $table) {
$table->increments('id');
$table->decimal('original_price', 10, 2);
$table->decimal('discouted_price', 10, 2);
$table->integer('city_id')->index()->unsigned()->nullable();
$table->foreign('city_id')->references('id')->on('cities');
$table->integer('destination_city_id')->unsigned()->index();
$table->foreign('destination_city_id')->references('id')->on('cities');
$table->string('url');
$table->string('titile');
$table->text('description')->nullable();
$table->dateTime('expires_at');
$table->integer('clicks')->default('0');
$table->integer('views')->default('0');
$table->timestamps();
$table->softDeletes();
});
现在我想从('listings')中删除这两个列
但是有人可以写这个新的迁移怎么必须在这两列上寻找删除 你可以这样做
if (Schema::hasColumn('city_id', 'destination_city_id'))
{
$table->dropForeign('city_id');
$table->dropForeign('destination_city_id');
$table->dropColumn(['city_id', 'destination_city_id']);
}
最好检查表中是否存在相关列
试试看,这应该可以用。L5.8中Laravel Schema Builder中hasColumn的函数如下所示:
\vendor\laravel\framework\src\Illuminate\Database\Schema\Builder::hasColumn($table,$column)
{
return in_array(
strtolower($column), array_map('strtolower',$this->getColumnListing($table)));
因此,您应该使用表名作为第一个参数,如下所示
public function up() {
if(Schema::hasColumn('listings','city_id')) {
Schema::table('listings',function (Blueprint $table) {
$table->dropColumn('city_id');
});
}
}
对要删除的每个列重复上述操作首先从数据库中删除表,然后从迁移文件中删除此行,然后使用命令再次迁移表:
php artisan migrate
Nope,我必须为此进行新的迁移。我不必从列表表中删除这两列。要删除一列,您可以使用架构生成器上的dropColumn
方法。在删除列之前,请确保将原则/dbal
依赖项添加到composer.json
文件中。
public function up() {
if(Schema::hasColumn('listings','city_id')) {
Schema::table('listings',function (Blueprint $table) {
$table->dropColumn('city_id');
});
}
}