doctrine dbal querybuilder as prepared statement

前端 未结 5 2005
故里飘歌
故里飘歌 2021-01-16 17:25

I\'m trying to create a Doctrine DBAL querybuilder object and setting a parameter in it. (using a postgres db, dbal 2.3.4, doctrine

$connection = $this->         


        
5条回答
  •  礼貌的吻别
    2021-01-16 18:05

    I ran into the same problem with DBAL 2.5.13.

    I'm writing a tool that uses Symfony components and DBAL, therefore there is no entityManager object but to maintain similar structure due team previous knowledge with Symfony, I made a repository class with a method like:

    public function getAtendimentoRealFromOffline($foo3, $foo4)
    {
        $query = $this->createQueryBuilder()
                        ->select("foo1, foo2")
                        ->from("bar_table")
                        ->andWhere("foo3 = :foo3")
                        ->andWhere("foo4 = :foo4")
                        ->setParameter(":foo3", $foo3)
                        ->setParameter(":foo4", $foo4);
    }
    

    Now if you run like:

    $this->connection->fetchAll($query);
    

    It will indeed show you the error, because you're using the fetchAll from connection with no relation at all with the statement you just created with QueryBuilder. One solution would be use the second parameter to send an array of parameters:

    $this->connection->fetchAll($query, ["foo3" => "bar3", "foo4" => "bar4"]);
    

    and you can remove the setParameters from the query builder:

        $query = $this->createQueryBuilder()
                        ->select("foo1, foo2")
                        ->from("bar_table")
                        ->andWhere("foo3 = :foo3")
                        ->andWhere("foo4 = :foo4")
    

    What can be unseen by the documentation is that the QueryBuilder actually has an execute method, which will then indeed run with the parameters, therefore you can just:

    $query->execute()->fetchAll();
    

提交回复
热议问题