【发布时间】:2018-09-21 14:59:36
【问题描述】:
我正在使用 postgresql。我正在使用这个命令创建一个数据库:
<?php
namespace efsystem\Console\Commands;
use Illuminate\Console\Command;
class CreatePostgressDatabase 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 = config('database.connections.pgsql.database');
$dbuser = config('database.connections.pgsql.username');
$dbpass = config('database.connections.pgsql.password');
$dbhost = config('database.connections.pgsql.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()));
}
}
}
它工作正常,但我也想在那个数据库中创建几个模式。我尝试在迁移文件中使用 db::unprepared 但它不起作用,因为要进行迁移,它需要之前创建架构。
EDIT1:我尝试使用此迁移创建架构:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSchemaAdministracion extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
DB::unprepared('
CREATE SCHEMA administracion
');
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
DB::unprepared('DROP SCHEMA `administracion`');
}
}
但我得到:无效的架构名称:7 错误:未选择架构。
【问题讨论】:
-
您可能需要为您的用户授予对新数据库的权限? (我通常使用 MySQL,所以这个建议可能没用!)
-
不,我不这么认为。我只想创建模式。
-
您是否尝试过使用迁移来创建架构?
-
我试过了,但我认为我做错了。我只是编辑我的答案。
标签: php laravel postgresql laravel-5