Laravel 5.6:在数据库中创建模式

3

我正在使用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,但它不起作用,因为在进行迁移之前需要先创建模式。

编辑1:我尝试使用此迁移创建模式:

<?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,所以这个建议可能毫无用处!) - miken32
1
不,我不这么认为。我只想创建模式。 - alfredjmg
你尝试使用迁移来创建模式了吗? - Rob W
我尝试过了,但我觉得我做错了。我刚刚编辑了我的答案。 - alfredjmg
我希望你注意到了你的拼写错误!可惜没有其他人注意到...管理* - Sunhat
1个回答

1
这将有所帮助:

        public function up()
    {
        DB::connection($this->getConnection())->unprepared("
        SET search_path to public;
        CREATE SCHEMA administracion;
        SET search_path to administracion;
    ");
    }

    public function down()
    {
        DB::connection($this->getConnection())->unprepared("
        DROP SCHEMA IF EXISTS administracion;
");
    }

1
考虑到没有进一步对该模式进行操作,SET search_path to administracion; 的目的是什么?实际上,应该将模式设置回包含 Laravel 内置 migrations 表的模式。根据我的经验,如果不这样做,当 Laravel 尝试在成功时插入记录时会引发异常:Undefined table: 7 ERROR: relation "migrations" does not exist - Ben Johnson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接