how can i write native sql queries with doctrine in symfony ?
Asked
Active
Viewed 4,824 times
0
-
"Complex queries" is very abstract. What do you mean by this ? Writing raw SQL ? DQL ? You can still write raw SQL in Doctrine thanks to the Doctrine DBAL layer. http://stackoverflow.com/questions/3325012/execute-raw-sql-using-doctrine-2/9945711#9945711 – MeuhMeuh Jul 31 '15 at 08:18
1 Answers
1
$connection = $this->getDoctrine()->getManager()->getConnection();
$connection is now a class Doctrine\DBAL\Connection check the docs http://www.doctrine-project.org/api/dbal/2.1/class-Doctrine.DBAL.Connection.html
This code should help you.
$connection = $this->getDoctrine()->getManager()->getConnection();
$query = "
INSERT INTO data (
name
, age
) VALUES (
?
, ?
)
";
$connection->executeQuery(
$query
, array(
'test'
, 30
)
, array(
\PDO::PARAM_INT
,\PDO::PARAM_STR
)
);
Or
$connection = $this->getDoctrine()->getManager()->getConnection();
$name = 'test';
$age = 31;
$query = "
INSERT INTO data (
name
, age
) VALUES (
:name
, :age
)
";
$statement = $connection->prepare($sql);
$statement->bindValue("name", $name, \PDO::PARAM_INT);
$statement->bindValue("age", $age, \PDO::PARAM_STR);
$statement->execute();

Raymond Nijland
- 11,488
- 2
- 22
- 34