gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 10:45:24 24 4
gpt4 key购买 nike

我在我的一个项目中使用了 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
}

仅在迁移文件中,但我从未尝试过这种方式,我将其保留以备最后解决。请指导和帮助我。

最佳答案

我在查找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();
});
}
}
}

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

关于php - 在 laravel 5.6 中迁移时如何检查 mongo 集合是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53700033/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com