Execute custom SQL in symfony

為{幸葍}努か 提交于 2019-12-03 16:34:48
$query = "SELECT * from something complicated";
$rs = Doctrine_Manager::getInstance()->getCurrentConnection()->fetchAssoc($query);

The resultset is an array.

// get Doctrine_Connection object
$con = Doctrine_Manager::getInstance()->connection();
// execute SQL query, receive Doctrine_Connection_Statement
$st = $con->execute("SELECT User.* FROM ....");
// fetch query result
$result = $st->fetchAll();

// convert array to objects
foreach ($result as $userArray) {
    $user = new User();
    $user->fromArray($userArray);
    ...
}

This code is not very short but allows to execute custom query via existing Doctrine connection and receive your object in the end.

To answer your question (this is done from a task):

$databaseManager = new sfDatabaseManager ( $this->configuration );
Doctrine_Manager::connection ()->setAttribute ( Doctrine_Core::ATTR_AUTO_FREE_QUERY_OBJECTS, true );

$dbOptions = Doctrine_Manager::connection ()->getManager ()->getConnection ( 'doctrine' )->getOptions ();
$dbDsn = $dbOptions['dsn'];
$dbDsnArr = explode ( ';', $dbDsn );
$dbHost = str_replace ( 'mysql:host=', '', $dbDsnArr[0] );
$dbName = str_replace ( 'dbname=', '', $dbDsnArr[1] );
$dbUn = $dbOptions['username'];
$dbPw = $dbOptions['password'];

Assuming the DSN is configured as such: dsn: 'mysql:host=somedomain;dbname=dbname'

This code allows you to retrieve the database connection information of any connection, so it will work for multiple connections as well

I hope this helps...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!