【问题标题】:Laravel (6.0.3) doesn't flush DB::statement commands?Laravel (6.0.3) 不刷新 DB::statement 命令?
【发布时间】:2020-02-13 19:11:41
【问题描述】:

Laravel (6.0.3):在我的迁移任务中,我想手动(使用自定义 sql)创建表并执行恢复控制台命令,因此我使用 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】:

    好的,最后我改变了策略并解决了实现新的自定义数据库连接并在调用任何终端命令之前使用它的问题。

    我用这样的代码创建了一个 Helper:

    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;
      }
    }
    
    

    【讨论】:

      猜你喜欢
      • 2019-04-03
      • 2018-07-15
      • 2021-09-06
      • 1970-01-01
      • 2017-01-15
      • 2020-10-03
      • 2010-10-21
      • 2018-10-03
      • 2017-12-15
      相关资源
      最近更新 更多