我在我的一个项目中使用laravel 5.6,mongodb和mysql。我使用了jessengers mongodb软件包,并通过它为3个集合创建了架构,尽管mongodb是较少架构的数据库,但是出于文档目的,我创建了架构。示例之一是:
<?php
use Jenssegers\Mongodb\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
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
}
仅在迁移文件中,但我从未尝试过这种方法,我将其保留为上一个解决方案。请指导并帮助我。
答案 0 :(得分:0)
我搜索了laravel的文档后得到了解决方案。
有一种方法叫:hasTable()
,它返回boolean
值是否表示集合/表是否存在。
这是我的工作方式,现在工作正常:
<?php
use Jenssegers\Mongodb\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
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();
});
}
}
}
我希望将来有人能从该解决方案中受益。