Репозиторий (построитель запросов)
Код: Выделить всё
class CustomerRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Customer::class);
}
public function getCustomers(
string $column,
string $type,
int $page = 1,
int $entriesPerPage = 10): array
{
$query = $this->createQueryBuilder('d')
->orderBy("d.$column", $type)
->getQuery();
$query->setFirstResult($entriesPerPage * ($page - 1))
->setMaxResults($entriesPerPage);
$paginator = new Paginator($query);
$total = $paginator->count();
$lastPage = (int)ceil($total / $entriesPerPage);
return [
'customers' => $paginator,
'lastPage' => $lastPage,
'total' => $total
];
}
}
Код: Выделить всё
#[Route(path: "/api/customers/{column}/{type}/{page}", name: "customer_get", methods: ["GET"])]
public function getCustomers(
CustomerService $customerService,
string $column,
string $type,
int $page=1
): JsonResponse
{
return $this->json($customerService->getCustomers($column, $type, $page));
}
Код: Выделить всё
{
"customers": [
{
"id": 156,
"name": "Test",
"created_at": "2024/03/07",
"updated_at": null
},
{
"id": 157,
"name": "Test",
"created_at": "2024/03/07",
"updated_at": null
}
],
"lastPage": 3,
"total": 11
}
Код: Выделить всё
const [sortBy, setSortBy] = useState({field: "name", order: "ASC"});
const [sortByCreatedAt, setSortByCreatedAt] = useState(null);
const fetchCustomers = () => {
const sortField = sortByCreatedAt ? 'created_at' : sortBy.field;
const sortOrder = sortByCreatedAt ? sortByCreatedAt.order : sortBy.order;
axios.get(`/api/customers/${sortField}/${sortOrder}/${currentPage}`)
.then(response => {
setCustomers(response.data.departments);
setLastPage(response.data.lastPage)
})
.catch(error => {
console.error(error);
});
};
Есть ли какие-либо возможности улучшить предложение «Упорядочить по» в построителе запросов? Можно ли сделать его более динамичным или и так нормально?
Подробнее здесь: https://stackoverflow.com/questions/781 ... pagination