简体   繁体   中英

Set a non-default schema in Yii Framework with PostgreSQL

I'm using Yii Framework with PostgreSQL and I need to create new models in a non-default schema. How can I do that? I tried the following:

protected/components/PgSchemaConnection.php

class PgSchemaConnection extends CDbConnection {
  protected function initConnection($pdo)
  {
    parent::initConnection($pdo);
    $stmt=$pdo->prepare("set search_path to master, public");
    $stmt->execute();
  }
}

protected/config/main.php

return array(
    ...
    'db'=>array(
            'connectionString' => 'pgsql:host=localhost;dbname=bsc',
        'username' => 'aUser',
        'password' => 'aPass',
        'charset' => 'utf8',
            'class' => 'PgSchemaConnection'
        ),
    ...
)

But when I run in console

>> model Foo
Warning: the table 'Foo' does not exist in the database.
   generate models/relatedobjective.php
PHP Warning:  Invalid argument supplied for foreach() in /home/cristhian/php_apps/yii-1.1.14.f0fee9/framework/cli/views/shell/model/fixture.php on line 13
PHP Warning:  Invalid argument supplied for foreach() in /home/cristhian/php_apps/yii-1.1.14.f0fee9/framework/cli/views/shell/model/fixture.php on line 19
   generate fixtures/relatedobjective.php
   generate unit/relatedobjectiveTest.php

The following model classes are successfully generated:
    relatedobjective

If you have a 'db' database connection, you can test these models now with:
    $model=relatedobjective::model()->find();
    print_r($model);

Yii does not find the table Foo in the database (Obiously, I have been created the Foo table)

How can I set another schema? What am I doing wrong?

just provide the full path to your table - including schema name.

With gii, I set 'tableName' field with 'schemaName.tableName'.

Your model will look like:

class MyModel extends CActiveRecord{
    ...
    tableName(){
        return 'schemaName.tableName';
    }

This model will perform queries with your default 'db' connection config.

you have to change the database connection of that model,

you can overwrite the getDbConnection() of that model to use another connection:

public function getDbConnection()
{
    return Yii::app()->dbPostgre;
}

and now add this connection below your main database connection in config/main.php

'dbPostgre' => array(
    'connectionString' => 'pgsql:host=localhost;dbname=bsc',
    'class'=>'CDbConnection',
    'username' => 'aUser',
    'password' => 'aPass',
    'charset' => 'utf8',
        'class' => 'PgSchemaConnection'
    ),
),

now your good to go,

but one thing, if you want to use gii to generate model from that database, temporarily change the name of dbPostgre to db

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM