@@ -23,6 +23,23 @@ public function __construct(ManagerRegistry $registry)
2323 parent ::__construct ($ registry , CalendarInstance::class);
2424 }
2525
26+ /**
27+ * Returns every instance the principal has, with its `calendars` row already loaded. Every
28+ * caller reads it, so leaving it lazy costs one extra query per calendar.
29+ *
30+ * @return CalendarInstance[]
31+ */
32+ public function findByPrincipalUriWithCalendars (string $ principalUri ): array
33+ {
34+ return $ this ->createQueryBuilder ('c ' )
35+ ->addSelect ('cal ' )
36+ ->join ('c.calendar ' , 'cal ' )
37+ ->where ('c.principalUri = :principalUri ' )
38+ ->setParameter ('principalUri ' , $ principalUri )
39+ ->getQuery ()
40+ ->getResult ();
41+ }
42+
2643 /**
2744 * @return CalendarInstance[] Returns an array of CalendarInstance objects
2845 */
@@ -118,6 +135,38 @@ public function findAllSchedulingObjectsForCalendar(int $calendarInstanceId, str
118135 ->getResult ();
119136 }
120137
138+ /**
139+ * Counts the objects of several calendars at once, so that listing a principal's calendars
140+ * costs a single query instead of one per calendar.
141+ *
142+ * @param int[] $calendarIds
143+ *
144+ * @return array<int, int> count per calendar id, including the calendars that hold nothing
145+ */
146+ public function countObjectsByCalendar (array $ calendarIds ): array
147+ {
148+ $ counts = array_fill_keys ($ calendarIds , 0 );
149+
150+ if (!$ calendarIds ) {
151+ return $ counts ;
152+ }
153+
154+ $ results = $ this ->getEntityManager ()->getRepository (CalendarObject::class)
155+ ->createQueryBuilder ('o ' )
156+ ->select ('IDENTITY(o.calendar) AS calendarId, COUNT(o.id) AS count ' )
157+ ->where ('o.calendar IN (:calendarIds) ' )
158+ ->setParameter ('calendarIds ' , $ calendarIds )
159+ ->groupBy ('o.calendar ' )
160+ ->getQuery ()
161+ ->getResult ();
162+
163+ foreach ($ results as $ result ) {
164+ $ counts [(int ) $ result ['calendarId ' ]] = (int ) $ result ['count ' ];
165+ }
166+
167+ return $ counts ;
168+ }
169+
121170 /**
122171 * Get counts of calendar objects by component type for a calendar instance.
123172 *
0 commit comments