'how can i get previous and current month results in symfony repository
what a good day to all of you, I am developing an app related to sales in the framework of Symfony Version 5.4 in which I am having problems to consult the database using the repository, I need to obtain the sums of the daily sales by advisor during the previous month and also all daily sales per advisor only in the current month.
my database data
suppose the following data I have a user with advisor ROLE1 which has 3 clients each customer has the next sale date ["2022-02-02","2022-03-02","2022-04-04"] with its respective amount ["1200","50","55"] formed from the date (Y-m-d)
then the controller
#[Route('/dashboard', name: 'dashboard')]
public function index(UserRepository $userRepository, ClienteRepository $repository, Request $request): Response
{
$user = $this->container->get('security.token_storage')->getToken()->getUser();
$asesores = $userRepository->findByRoles('ROLE_ASESOR');
foreach ($asesores as $key => $asesor) {
$ventasdelmesanteriorasesor = $repository->getCountVentasMesAnteriorAsesores($asesor->getPerson()->getId());
if (count($ventasdelmesanteriorasesor) == 0) {
$datos[$asesor->getUsername()]['ventamesanteriorasesor'] = null;
$datos[$asesor->getUsername()]['contadorventadelmesanteriorasesor'] = 0;
}
foreach ($ventasdelmesanteriorasesor as $ventadelmesanteriorasesor) {
$datos[$asesor->getUsername()]['ventamesanteriorasesor'][] = $ventadelmesanteriorasesor['mes'];
$datos[$asesor->getUsername()]['contadorventadelmesanteriorasesor'][] = $ventadelmesanteriorasesor['montoanterior'];
}
return $this->render('dashboard/index.html.twig', [
'ventamesanteriorasesor1' => json_encode($datos['asesor1']['ventamesanteriorasesor']),
'contadorventadelmesanteriorasesor1' => json_encode($datos['asesor1']['contadorventadelmesanteriorasesor']),
]);
}
now the query in the repository SQL
public function getCountVentasMesAnteriorAsesores($idAsesor)
{
$query = $this->createQueryBuilder('a')
->select("SUBSTRING(a.fechaventa, 1, 10)as mes, (a.monto) as montoanterior")
->where("a.fechaventa >= :mes")
->setParameter("mes", date('Y-m', strtotime('-1 month')))
->join('a.asesor', 'b')
->andwhere('b.id = :idAsesor')
->setParameter('idAsesor', $idAsesor)
->groupBy("mes")
->getQuery()
->getScalarResult();
return $query;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

