【问题标题】:In Symfony 1.2 how can I get the current database name from the database.yml file in Propel?在 Symfony 1.2 中,如何从 Propel 中的 database.yml 文件中获取当前数据库名称?
【发布时间】:2010-05-14 21:09:35
【问题描述】:

我有一个原始的 sql 查询需要运行,但是每个环境中的数据库名称都会发生变化(live: db, dev db_test)

我需要从 databases.yml 文件中获取当前数据库名称。

如何获取当前数据库名称?

我正在使用 Propel ORM

【问题讨论】:

  • 是否可以使用当前的数据库连接,还是真的需要数据库名自己创建连接?如果你使用“常规”Propel,你可以使用Propel::getConnection() 来获得 PDO 连接,我想你也可以在 Symfony 中这样做。

标签: database symfony1 propel


【解决方案1】:

最初我认为通过sfPropelDatabase::getConfiguration() 会很容易,但它返回一个数组。因此,我不得不解析结果来获取数据,我认为可能有比这更好的方法:

$propel_config = sfPropelDatabase::getConfiguration();
preg_match('/dbname=([^;]+);/', $propel_config['propel']['datasources']['propel']['connection']['dsn'], $matches);
echo $matches[1];

谁有更好的?

【讨论】:

  • 如果除了获取 yaml 文件的转储之外还有更多控制权,那就太好了。我不得不删除';'从上面的正则表达式,因为 dbname 是最后一个字符,它在字符串的末尾找不到它。
【解决方案2】:

以下代码在 Propel2 中有效——与接受的答案基本相同。

$mgr = \Propel\Runtime\Propel::getConnectionManager($connectionId);
$dsn = $mgr->getConfiguration()['dsn'];
preg_match('/dbname=([^;]+)/', $dsn, $matches);
echo $matches[1];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-29
    • 2017-12-27
    • 2012-05-23
    • 2011-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多