我想使用命令创建数据库。我正在使用postgresql。我正在使用迁移来创建表,但是在此之前,我想创建数据库和几个模式。 我正在使用以下命令:
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()));
}
}
}
但是我得到这个错误:
Failed to create database: SQLSTATE[08006] [7] could not translate host name "connect_timeout=30" to address: Unknown server error
就像我说过的那样,我想在Laravel中创建一个新的数据库,我正在使用这种方式,但是没有用,如果我想知道还有其他方法可以使用。
EDIT1:现在可以正常工作,我只是从配置中选择值,就像您说的@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');