Execute custom SQL in symfony

2020-06-18 09:16发布

I'm trying to execute some custom SQL to retrieve some model objects in a Symfony application. I found a tutorial on the web that said something like this would allow me to execute the query although not populate the models (populating the model isn't a major issue, it's just for read only data).

$pdo = Doctrine_Manager::getInstance()->connection()->getDbh();
$pdo->prepare("SELECT * from something complicated");
$pdo->execute();
$this->sensorReadings = $pdo->fetchAll();

But I'm getting an error :

Fatal error: Call to undefined method PDO::execute()
in sfproject/apps/frontend/modules/site/actions/actions.class.php 

3条回答
三岁会撩人
2楼-- · 2020-06-18 10:00
$query = "SELECT * from something complicated";
$rs = Doctrine_Manager::getInstance()->getCurrentConnection()->fetchAssoc($query);

The resultset is an array.

查看更多
何必那么认真
3楼-- · 2020-06-18 10:04

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...

查看更多
聊天终结者
4楼-- · 2020-06-18 10:05
// 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.

查看更多
登录 后发表回答