Search code examples
symfonydoctrine-ormsymfony4query-builder

Symfony4 How to get objects with query builder


(Hi!), I need to get objects from a query builder, but I collect an array, so I have the following error:

Call to a member function getPropertyName() on array

So I suppose than my request isn't correct, but I don't know how to resolve my problem

public function findByYear($year): array
{
    $conn = $this->getEntityManager()->getConnection();

    $sql = 'SELECT * FROM rent_release r WHERE YEAR(`date`) = :yearRequested';
    $stmt = $conn->prepare($sql);
    $stmt->execute(['yearRequested' => $year]);

    return $stmt->fetchAll();
}

Waiting for your help, thanks :)


Solution

  • Ok so, according to comments, I used createQueryBuilder and beberlei/doctrineextensions.

    here is the DQL:

    $qb = $this->createQueryBuilder('rr')
            ->andWhere('YEAR(rr.date) = :year')
            ->setParameter('year', $year)
            ->orderBy('rr.date', 'ASC')
            ->getQuery();
    
        return $qb->execute();
    

    and in doctrine.yaml I added this:

    dql:
          string_functions:
            YEAR: DoctrineExtensions\Query\Mysql\Year
    

    and now it works well, thanks all !