Mgulizia
Mgulizia

Reputation: 3

PHP Symfony sorting entities using Doctrine entity attribute and associated entity attributes

So i have an entity called a Service where users can go and report about their day, and another entity called a visit that has the reported information about individual visits the user had that day. its a one to many relationship. one form to many visits.

The form has the date the visit has the visit start and stop times.

I am trying to create a report that shows every form created that month sorted by first the form.date then by the visit.startTime. but for the life of me, i cannot figure this out. Maybe i am overthinking it.

I got it working for forms that have many visits by creating a Twig filter that sorts the visits by startTime.. but that isn't a good way of doing it.. I'm sure it needs to be done in the repository, but i can't for the life of me figure out how to get it to work.

Could some one out there maybe offer some advise on how to write the querybuilder to pull this off?

Upvotes: 0

Views: 313

Answers (1)

Łukasz Jakubek
Łukasz Jakubek

Reputation: 1013

You can do it in many ways, but best will be sort when query database. You can retrieve data from database using Doctrine\ORM\QueryBuilder. Example:

// ServiceRepository
public function getServicesWithVisists() {
    $builder = $this->createQueryBuilder('s');
    $builder->select('s', 'v')
        ->leftJoin('s.visits', 'v')
        ->orderBy('s.date', 'ASC')
        ->addOrderBy('v.startTime', 'ASC');

    return $builder->getQuery()->getResult();
}

Upvotes: 2

Related Questions