Search code examples
phpsymfonydoctrinesymfony4

How to fetch data of an object when im getting the parent object (ex. process have actions, im fetching process) DOCTRINE


Let's say I have a class named Process, that has name, data.. etc. Then, this process class has a subclass called actions that have: [name, year, data]. So when I want to take all processes I just want to fetch the actions which have the year set in 2020 instead of getting all the actions with all the years.

Is there any way to do this in doctrine?

Something like SELECT PROCESS WHERE PROCESS.ACTIONS.YEAR LIKE 2020 (but in doctrine)

Sorry for the bad explanation, I hope you can understand it.

ps. I'm trying to print all processes in one twig file but I just want the latest actions.

Thank you very much


Solution

  • IF you have the relations defined correctly, you can do:

    SELECT process 
    FROM App\Entity\Process process 
    LEFT JOIN process.actions action 
    WHERE action.year = 2020
    

    or in the process repository

    return $this->createQueryBuilder('process')
        ->leftJoin('process.actions', 'action')
        ->where('action.year = 2020')
        ->getQuery()
        ->getResult();
    

    not certain if you get duplicates, though. In the DQL-Query you can probably just say SELECT DISTINCT process etc. And I'd guess in the query builder variant, you might have to add ->select('DISTINCT process') before the getQuery.