0

I have a schema which includes a one to many relationship between a Page and Report. Reports has a date field and I want to fetch a count of Reports per Page within a given time frame along with all the Page data and filtered Reports.

$this->createQueryBuilder('p')
            ->leftJoin('p.reports', 'page_reports')
            ->addSelect('page_reports')
            ->where('page_reports.datetime > :since')
            ->setParameter('since', new DateTime('-15 days'))
            ->getQuery()
            ->execute();

The above returns Page entities where the Reports collection is filtered by the date but I do not know how to additionally return a count of Reports per page while also maintaining the filtered Reports. Am I going about this the right way or should I be just querying for the Pages and then applying a filter to the Reports collection such as:

$criteria = Criteria::create()
   ->where(Criteria::expr()->gt("datetime", $since));
$reports = $page->getReports()->matching($criteria);

1 Answer 1

-1

Returning records, and counting records, usually needs to be 2 separate queries.

If you only need the count of records being returned by the first query, and assuming you are covering the "Reports per Page" with that query, then it already returns an array of objects, let's call it $result and you can use count($result).

Since I can't see the part of your code where the query result was used, that's the best answer I can offer so far.

2
  • Thanks. I did consider counting the collection array but I forgot to add in my original post that I also would like to sort by the count so it's sounding like multiple queries are needed.
    – James Hall
    Commented May 21 at 15:25
  • @JamesHall "sort by the count" doesn't have any context so far. What exactly are you trying to count? Did you want to sort the Pages? Do you need to expand your original question? Commented May 21 at 15:30

Not the answer you're looking for? Browse other questions tagged or ask your own question.