【问题标题】:Set a non-default schema in Yii Framework with PostgreSQL在 Yii 框架中使用 PostgreSQL 设置非默认模式
【发布时间】:2014-04-29 01:52:27
【问题描述】:

我正在使用 Yii 框架和 PostgreSQL,我需要在非默认模式中创建新模型。我怎样才能做到这一点? 我尝试了以下方法:

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'
        ),
    ...
)

但是当我在控制台中运行时

>> 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 在数据库中没有找到 Foo 表(很奇怪,我已经创建了 Foo 表)

如何设置另一个架构?我做错了什么?

【问题讨论】:

    标签: php postgresql yii database-schema


    【解决方案1】:

    只需提供表的完整路径 - 包括架构名称。

    使用 gii,我将“tableName”字段设置为“schemaName.tableName”。

    您的模型将如下所示:

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

    此模型将使用您的默认“db”连接配置执行查询。

    【讨论】:

      【解决方案2】:

      您必须更改该模型的数据库连接,

      您可以覆盖该模型的getDbConnection() 以使用另一个连接:

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

      现在将此连接添加到config/main.php中的主数据库连接下方

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

      现在你可以走了,

      但有一件事,如果你想使用gii从那个数据库生成模型,暂时把dbPostgre的名字改成db

      【讨论】:

      • 感谢您的回答@tinybyte,但我认为我的代码和您的代码之间没有实质性区别。我做错了什么?
      猜你喜欢
      • 2013-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-31
      • 1970-01-01
      • 2020-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多