Search code examples
symfonydoctrine-ormdql

Error with a query in Doctrine2


I'm trying to build a query using Doctrine2 QueryBuilder, but this is what I get:

[Syntax Error] line 0, col 198: Error: Expected end of string, got 'lo' (500 Internal Server Error)

public function FiltrarDatos($localidad_id){
    $em = $this->getEntityManager();
    $dql = 'SELECT l FROM TarifaBundle:Llamada l';
    if ($localidad_id != "") {
        $dql.=' INNER JOIN l.localidad lo';
    }
    $dql.= ' WHERE';
    $bool = false;
    if ($localidad_id != '') {
        if ($bool)
            $dql.=' AND';
        $dql.=' lo.id=:localidad_id';
        $bool = true;
        $parameters['localidad_id'] = $localidad_id;
    }
    $query = $em->createQuery($dql);
    $query->setParameters($parameters);

    return $query->getResult();

}

Solution

  • There are some problems in your SQL.

    First: The function parameter $id_localidad is different from this line:

    if ($localidad_id != '') {
    

    Second, you always add a WHERE without a following expression if the function parameter is empty/null which result in a SQL error. Also the next lines don't make sense:

    if ($bool)
        $dql.=' AND';
    

    $bool will always be false so the AND isn't needed.

    Maybe some messy code because of try and error.