Laravel(6.0.3)不会刷新DB :: statement命令吗?

问题描述 投票:0回答:1

Laravel(6.0.3):在我的迁移任务中,我想手动(使用自定义sql)创建表并执行restore控制台命令,所以我已经使用up()函数创建了文件database/migrations/today_date_create_my_custom_tables.php

use Illuminate\Support\Facades\DB;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\QueryException;

class CreateMyTables extends Migration
{
    public function up()
    {
        // ...
        try {
            \Log::info('create tables...');
            $result = DB::statement($a_lot_of_sql_commands_creating_tables_read_from_file);
            \Log::info('DB::statement executed... but...');
            \Log::info('also if I wait seconds...');
            sleep(3);
            \Log::info('try to call my working custom console command "pg_restore"...');
            $exitCode = Artisan::call('db:restore'); // it call pg_restore server command
            \Log::info('...give error: tables aren\'t created yet.');
            // here I need to do a lot of other stuff (create foreign keys, ecc..),
            // but data must be restored.
        }
        catch (QueryException $e) {
            //...
        }
    }
}

我使用postgresql。我的自定义工匠控制台命令db:restore起作用。我的数据是二进制格式,因此只有pg_restore可以将它们放回去。

[如果我在睡眠行中(应创建表之后)检查数据库(例如,使用pgAdmin进行检查),我发现表尚不存在。似乎所有DB命令都在函数结束(或db连接?)结束后刷新,因此我仅在迁移完成后才能看到表。

我想在迁移命令中合并其他内容,但是如果未还原数据,我将无法连接。您是否知道如何立即刷新数据库命令,或以其他方式解决该问题?非常感谢!

php database laravel postgresql flush
1个回答
0
投票
好,最后,我改变了策略,解决了在调用任何终端命令之前实现新的自定义数据库连接并使用它的问题。

我用这样的代码创建了一个帮助器:

namespace App\Helpers; class MyDB { /** * Custom DB connection */ public static $dbConnection; /** * Create the connection resource to the DB */ public static function connectDB () { $connectionString = 'user='.env('DB_DATABASE'); $connectionString .= ' password='.env('DB_PASSWORD'); $connectionString .= ' host='.env('DB_HOST'); $connectionString .= ' port='.env('DB_PORT'); $connectionString .= ' dbname='.env('DB_DATABASE'); MyDB::$dbConnection = pg_pconnect($connectionString); } /** * Execute a Statement query with the custom DB connection. */ public static function executeStatement ($query) { if (is_null(MyDB::$dbConnection)) { MyDB::connectDB(); } $resource = pg_query(MyDB::$dbConnection, $query); if ($resource === false) { return false; } return true; } }

© www.soinside.com 2019 - 2024. All rights reserved.