如何在laravel 5.6中迁移时检查mongo集合是否存在



我在一个项目中使用了laravel 5.6、mongodb和mysql。我使用了jessengers mongodb包,通过它我为我的3个集合创建了模式,尽管mongodb是无模式数据库,但出于文档目的,我创建了模式。其中一个例子是:

<?php
use JenssegersMongodbSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;
class CreateChatMessagesTable extends Migration
{
/**
* The name of the database connection to use.
*
* @var string
*/
protected $connection = 'mongodb';

/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::connection($this->connection)->create('chat_messages', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->integer('trade_id');
$table->tinyInteger('type')->default('1');
$table->text('content');
$table->integer('recipient_id');
$table->timestamp('recipient_read_at')->nullable();
$table->timestamp('created_at')->nullable();
$table->tinyInteger('status')->default('1');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::connection($this->connection)
->table('chat_messages', function (Blueprint $collection)
{
$collection->drop();
});
}
}

这里的问题是,每当我运行php artisan migrate:fresh命令时,它都会给我一个类似collection already exists的错误。我需要检查,特别是对于mongodb,如果集合存在,那么不要再次迁移该集合。

我想我应该运行一个类似的查询

if(true == ChatMessage::get()){
//do not run the migration
} else{
//continue the migration
}

仅在迁移文件中,但我从未尝试过这种方式,我将其保留到最后一个解决方案中。请引导并帮助我。

我在搜索laravel的文档后得到了解决方案。

有一个方法名为:hasTable(),无论集合/表是否存在,它都会返回boolean值。

我就是这样做的,现在运行良好:

<?php
use JenssegersMongodbSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;
class CreateChatMessagesTable extends Migration
{
/**
* The name of the database connection to use.
*
* @var string
*/
protected $connection = 'mongodb';

/**
* Run the migrations.
*
* @return void
*/
public function up()
{
if(Schema::connection($this->connection)->hasTable('chat_messages') == false) {
Schema::connection($this->connection)->create('chat_messages', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->integer('trade_id');
$table->tinyInteger('type')->default('1');
$table->text('content');
$table->integer('recipient_id');
$table->timestamp('recipient_read_at')->nullable();
$table->timestamp('created_at')->nullable();
$table->tinyInteger('status')->default('1');
});
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
if(Schema::connection($this->connection)->hasTable('chat_messages') == false) {
Schema::connection($this->connection)
->table('chat_messages', function (Blueprint $collection) {
$collection->drop();
});
}
}
}

我希望将来有人会从这个解决方案中受益。

最新更新