Execute custom SQL in symfony

15,532

Solution 1

$query = "SELECT * from something complicated";
$rs = Doctrine_Manager::getInstance()->getCurrentConnection()->fetchAssoc($query);

The resultset is an array.

Solution 2

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

Share:
15,532
BenCr
Author by

BenCr

Silverlight Developer/Martyr

Updated on June 04, 2022

Comments

  • BenCr
    BenCr almost 2 years

    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