У меня уже есть имя таблицы table_one.. Теперь я хочу добавить к ней еще два столбца. Пока все работает нормально. Но в моем методе я хочу проверить, существует ли столбец в моей таблице, например dropIfExists('table')..
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('table_one', function (Blueprint $table) {
$table->string('column_one')->nullable();
$table->string('column_two')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('table_one', function (Blueprint $table) {
// in here i want to check column_one and column_two exists or not
$table->dropColumn('column_one');
$table->dropColumn('column_two');
});
}






Вам нужно что-то вроде этого
public function down()
{
if (Schema::hasColumn('users', 'phone'))
{
Schema::table('users', function (Blueprint $table)
{
$table->dropColumn('phone');
});
}
}
Просто разбейте схему на два вызова
public function up()
{
Schema::table('table_one', function (Blueprint $table) {
$table->dropColumn(['column_one', 'column_two']);
});
Schema::table('table_one', function (Blueprint $table) {
$table->string('column_one')->nullable();
$table->string('column_two')->nullable();
});
}
Это приведет к удалению и всех данных в этих столбцах! Очень опасный код!
Вы можете создать свою собственную функцию dropColumnIfExists (), которая проверяет наличие столбца, а затем отбросить ее:
function myDropColumnIfExists($myTable, $column)
{
if (Schema::hasColumn($myTable, $column)) //check the column
{
Schema::table($myTable, function (Blueprint $table)
{
$table->dropColumn($column); //drop it
});
}
}
И используйте его для функции down () следующим образом:
public function down()
{
myDropColumnIfExists('table_one', 'column_two');
myDropColumnIfExists('table_one', 'column_one');
}
Пожалуйста, всегда предоставляйте некоторые пояснения, а не просто фрагмент кода.
Если вы действительно хотите, чтобы это было внутри закрытия Schema::table, что является единственным изящным способом сделать это ... вам нужно либо добавить пару методов в Blueprint, либо использовать этот шаблон при каждой миграции ... это не красиво, но как только он появится, вы можете определить столько условных добавлений и отбрасываний, сколько захотите, используя только 1 строку в каждой.
return new class extends Migration {
public function up() {
Schema::table('tblAnimal', function (Blueprint $table) {
$exists = function (string $column) use ($table) {
return (Schema::hasColumn($table->getTable(), $column));
};
$addUnlessExists = function (string $type, string $name, array $parameters = [])
use ($table, $exists) {
return $exists($name) ? null : $table->addColumn($type, $name, $parameters);
};
$dropIfExists = function (string $column) use ($table, $exists) {
return $exists($column) ? $table->dropColumn($column) : null;
};
$dropIfExists('column_name');
$addUnlessExists('integer', 'int_column');
# ...
});
Спасибо. Ваше решение сработало нормально. Но мне такой подход не понравился. Я хотел что-то вроде dropIfExists ('column').