質問

I works on Symfony2 and try to execute all queries with Doctrine.

I'm a newbie with all possible syntax, sorry if it's a noob question...

On my model, I have some "Professionals" which get multiple "Reviews". I want to get some Professionals, with extendables limitations, and for each, just the latest Review.

I tried this :

    $dql = "    SELECT 
                    Pro,
                    review
                FROM 
                    Pro
                LEFT JOIN (
                    SELECT Review FROM Review WHERE Review.id = Pro.id ORDER BY Review.date_crea LIMIT 1
                ) AS review
    ";
    $em = $this->getEntityManager();
    $rsm = new \Doctrine\ORM\Query\ResultSetMappingBuilder($em);
    $rsm->addRootEntityFromClassMetadata('MyProject\Bundle\FrontBundle\Entity\Pro', 'p');
    $query = $em->createNativeQuery($dql, $rsm);

But I get this error :

SQLSTATE[42601]: Syntax error: 7 ERROR: syntax error at end of input LINE 9

This is my last try, I did this with different method and object on Doctrine, like createNativeQuery, createQuery, createQueryBuilder...

Does anybody succeed to do that ?

Thanks !

役に立ちましたか?

解決

Try this

            SELECT 
                Pro,
                r.Review
            FROM 
                Pro
            LEFT JOIN (
                SELECT Review.id as id,Review FROM Review 
                group by Review.id 
                having Max(Review.date_create)
            ) AS r on Pro.id=r.id

Edit having replaced with window function

       SELECT 
            Pro,
            r.review
        FROM 
            Pro
        LEFT JOIN (
            SELECT Review.id as id,Review, (rank()  over( partition by Review.id order by  Review.date_create )) as hit FROM Review 
        ) AS r on Pro.id=r.id and r.hit=1;
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top