PHP code example of rgalstyan / symfony-aggregated-queries
1. Go to this page and download the library: Download rgalstyan/symfony-aggregated-queries library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
rgalstyan / symfony-aggregated-queries example snippets
namespace App\Service;
use App\Repository\PartnerRepository;
class PartnerService
{
public function __construct(
private readonly PartnerRepository $partnerRepository
) {}
public function getAllPartnersForApi(): array
{
$partners = $this->partnerRepository->findAllOptimized();
// Transform to API format if needed
return array_map(fn($p) => [
'id' => $p['id'],
'name' => $p['name'],
'profile' => $p['profile'],
'country' => $p['country'],
'promocode_count' => $p['promocodes_count'],
], $partners);
}
}
namespace App\Controller;
use App\Service\PartnerService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
class PartnerController extends AbstractController
{
public function __construct(
private readonly PartnerService $partnerService
) {}
#[Route('/api/partners', methods: ['GET'])]
public function index(): JsonResponse
{
$partners = $this->partnerService->getAllPartnersForApi();
return $this->json($partners);
}
}
->getResult() // array (default, fastest)
->getResult('array') // Same as above
->getResult('entity') // Hydrate into Doctrine entities (slower)
->getOneOrNullResult() // Get first result or null
->toSql() // Get generated SQL
->getParameters() // Get query parameters
->debug() // Enable debug logging
use Doctrine\ORM\EntityManagerInterface;
class DataExportService
{
public function __construct(
private readonly PartnerRepository $partnerRepository,
private readonly EntityManagerInterface $em
) {}
public function exportPartners(): void
{
$batchSize = 500;
$offset = 0;
$csvFile = fopen('partners_export.csv', 'w');
do {
$partners = $this->partnerRepository->aggregatedQuery()
->withJsonRelation('profile', ['id', 'name', 'email'])
->withJsonRelation('country', ['id', 'name'])
->withCount('orders')
->orderBy('id', 'ASC')
->limit($batchSize)
->offset($offset)
->getResult();
if (empty($partners)) {
break;
}
foreach ($partners as $partner) {
fputcsv($csvFile, [
$partner['id'],
$partner['name'],
$partner['profile']['name'] ?? 'N/A',
$partner['country']['name'] ?? 'N/A',
$partner['orders_count'],
]);
}
$offset += $batchSize;
// Free memory
unset($partners);
$this->em->clear();
} while (true);
fclose($csvFile);
}
}