douna4762 2018-09-20 15:08
浏览 75

Laravel 5.6:使用命令创建新数据库时出错

I want to create a database using a command. I am using postgresql. I am creating the tables using the migrations but before that I want to create the database and several schemas. I am using this command:

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class pgsql extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'pgsql:createdb {name?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a new pgsql database schema based on the database config file';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $dbname = env('DB_DATABASE');
        $dbuser = env('DB_USERNAME');
        $dbpass = env('DB_PASSWORD');
        $dbhost = env('DB_HOST');

        try {
            $db = new \PDO("pgsql:host=$dbhost", $dbuser, $dbpass);
            $test = $db->exec("CREATE DATABASE \"$dbname\" WITH TEMPLATE = template0 encoding = 'UTF8' lc_collate='Spanish_Spain.1252' lc_ctype='Spanish_Spain.1252';");
            if($test === false) 
                throw new \Exception($db->errorInfo()[2]);
            $this->info(sprintf('Successfully created %s database', $dbname));
        }
        catch (\Exception $exception) {
            $this->error(sprintf('Failed to create %s database: %s', $dbname, $exception->getMessage()));
        }

    }
}

But I get this error:

Failed to create database: SQLSTATE[08006] [7] could not translate host name "connect_timeout=30" to address: Unknown server error

Like I said I want to create a new database in Laravel, I am using this way but is not working, if there is other way to do it I would like to know.

EDIT1: It works fine now, I just pick the values from the config like you said @Dimitri Mostrey :

$dbname = config('database.connections.pgsql.database');
$dbuser = config('database.connections.pgsql.username');
$dbpass = config('database.connections.pgsql.password');
$dbhost = config('database.connections.pgsql.host');
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥20 delta降尺度方法,未来数据怎么降尺度
    • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
    • ¥15 高德地图点聚合中Marker的位置无法实时更新
    • ¥15 DIFY API Endpoint 问题。
    • ¥20 sub地址DHCP问题
    • ¥15 delta降尺度计算的一些细节,有偿
    • ¥15 Arduino红外遥控代码有问题
    • ¥15 数值计算离散正交多项式
    • ¥30 数值计算均差系数编程
    • ¥15 redis-full-check比较 两个集群的数据出错