Please i have some trouble in my project in symfony
How can i replace having clause wuĆth where clause in this code above cause having clause dont work white paginator in symfony
...
...
public function getAllClients($all = true, $user = null)
{
$qb = $this->_em->createQueryBuilder();
//
$qb->select('u, count(ls.id) as nbr')
->from($this->_entityName, 'u')
->join(Client::class, 'c', Join::WITH, 'c.user = u.id')
->join(LicenceShop::class, 'ls', Join::WITH, 'ls.client = c.id')
->groupBy('u.id')
->having('nbr > 1');
$qb->andWhere('u.roles LIKE :roles');
$qb->setParameter('roles', '%"ROLE_CLIENT"%');
return $qb->getQuery();
}
Thanks you
When i use having clause symfony response like that
Cannot count query that uses a HAVING clause. Use the output walkers for pagination
And this the function
enter code public function show($id = null, UserRepository $userRepository, Request $request, PaginatorInterface $paginator)
{
if($id)
$user = $userRepository->find($id);
else
$user = $this->getUser();
$client = $user->getClientInfo();
$myClients = $userRepository->getAllClients(false, $user);
$myClients = $paginator->paginate(
$myClients,
$request->query->getInt('page_c', 100)
);
$referal = null;
$licences = null;
if ($client) {
$referal = $client->getReferal();
$licences = $client->getLicences();
}
//$licences = $module->getLicences();
return $this->render('resellers/show.html.twig', [
'controller_name' => 'ResellersController',
'user' => $user,
'client' => $client,
'referal' => $referal,
'licences' => $licences,
'my_clients' => $myClients,
]);
}
Related
I have a problem with my code, when a User have all "stations" the code work but if he dont have one i have the (undefined offset *) error,
my code look like that ( in my controller )
public function index()
{
$entityManager = $this->getDoctrine()->getManager();
$stations = $this->getListOfStations();
$stationsJson = [];
$events = $entityManager->getRepository('App:User')
->getEventInRealTime($this->getUser());
foreach ($stations as $station) {
$stationsJson[] = [
'typeEvents' => $events[$station->getId()],
];
}
return new JsonResponse(array('stations' => $stationsJson));
}
private function getListOfStations()
{
/** #var UserInterface $user */
$user = $this->getUser();
$entityManager = $this->getDoctrine()->getManager();
if (!$this->authorizationChecker->isGranted('ROLE_SUPER_ADMIN')) {
$stations = $user->getStations();
} else {
$stations = $entityManager->getRepository('App:Station')->findAll();
}
return $stations;
}
and my repository
public function getEventInRealTime($user)
{
$qb = $this->createQueryBuilder('u');
$events = $qb
->select('s.id as stationId, COUNT(e) as number, e.label as type')
->innerJoin('u.stations', 's')
->innerJoin('s.events', 'e')
->where('u = :user')
->setParameter('user', $user)
->andWhere('DAY(e.currentTime) =:day')
->setParameter('day', date('d'))
->andWhere('MONTH(e.currentTime) =:month')
->setParameter('month', date('m'))
->andWhere('YEAR(e.currentTime) =:year')
->setParameter('year', date('Y'))
->groupBy('s.id, type');
$data = $events->getQuery()->getArrayResult();
$result = [];
foreach ($data as $row) {
$result[$row['stationId']][] =
[
'number' => $row['number'],
'type' => $row['type']
];
}
return $result;
}
i think its a problem its like, he dont find the "stations" when i do a findAll(), but i dont know how to fix it, when the user is super_admin he can have see all the stations but if is not super admin he can see only his stations
I am writing a query which will return amount of total spent money for that user. Total spent = sum of all transaction amounts, where type = spend. I have set my type field in a base to 'spend'..
It returns
Invalid parameter: token type is not defined in the query.
My code.
public function getTotal(User $user, $type)
{
$query = $this->getSpendingRepository()
->createQueryBuilder('p')
->select("sum(p.amount) as total_amount")
->where('p.type = :spend')
->andWhere('p.user = :user')
->setParameters(['user' => $user,
'type' => $type])
->getQuery()
->getOneOrNullResult();
return $query;
}
and this is sql that is working so I don't know what am I doing wrong..
select user_id, sum(amount) as amount
from transaction
where type = 'spend'
group by user_id
Replace
->where('p.type = :spend')
with
->where('p.type = :type')
I fixed it.
public function getTotalSpent(User $user, $type = 'spend')
{
$query = $this->getTransactionRepository()
->createQueryBuilder('p')
->select("sum(p.amount) as total_amount")
->where('p.type = :type')
->andWhere('p.user = :user')
->setParameters(['user' => $user,
'type' => $type])
->getQuery()
->getOneOrNullResult();
return $query;
}
I am using the DoctrineMongoDBBundle and I am not sure how to prophesy the sort method.
Source
$qb = $dm->createQueryBuilder('Article')
->sort('createdAt', 'desc');
My code is:
UserRepository - Method All
public function all(array $input = null)
{
$user = UserEntity::class;
$all = $this->dm->createQueryBuilder($user);
$search = $all->sort(['name' => 'asc'])
->getQuery();
return $search;
}
UserRepositoryTest - prophecy
public function testSortingResults()
{
$output = [
'name' => 'John',
'email' => 'john#email.com',
'phone' => '89564789547',
];
$document = $this->prophesize(DocumentManager::class);
$queryBuilder = $this->prophesize(QueryBuilder::class);
$queryBuilder->sort()->willReturn($output)->shouldBeCalled();
$queryBuilder->getQuery()->willReturn($output)->shouldBeCalled();
$document->createQueryBuilder(UsuarioEntidade::class)->willReturn($queryBuilder)->shouldBeCalled();
$repository = new UserRepository($document->reveal());
$all = $repository->all();
$this->assertNotNull($all);
$this->assertEquals($output, $all);
}
The error is always this
Prophecy\Exception\Doubler\MethodNotFoundException: Method Double\Doctrine\ORM\QueryBuilder\P2::sort() is not defined.
I do not understand how to test SORT, because it is not found in QueryBuilder.
I'm using symfony 3, and I'm storing some data to database.
For this, the user does not have to be logged in.
Now I've created a select query with $this->getUser();. But the User can be NULL. When I execute this query, it does not select any rows.
return $this->createQueryBuilder('product')
->where('product.user = :user')
->andWhere('product.product = :product')
->andWhere('product.cartId = :uniqueCartId')
->setParameters([
'product' => $product,
'user' => $user,
'uniqueCartId' => $uniqueCartId
])
->getQuery()
->execute();
$user = $this->getUser();
I already tried this:
if(!$user instanceof User) $user = NULL;
But that does not work.
If I remove the User check, it works.
Any ideas?
I guess you should bind the where clause if there is an user object like
$parameters=array(
'product' => $product,
'uniqueCartId' => $uniqueCartId
);
$user = $this->getUser();
$query = $this->createQueryBuilder('product')
->where('product.product = :product')
->andWhere('product.cartId = :uniqueCartId');
if($user != null){ /* if($user instanceof User) */
$parameters['user'] = $user;
$query = $query->andWhere('product.user = :user');
}else{
/* $query = $query->andWhere('product.user IS NULL'); Not necessary */
}
$query->setParameters($parameters)
->getQuery()
->execute();
I'm working with Symfony2 and AJAX and have some problems, my controller returns old data from database. I tried var_dump variable before returning and everything was fine, but JsonResponse returns old data.
My controller:
public function returnOrderAction(Request $request)
{
$id = $request->request->get('id');
$em = $this->getDoctrine()->getManager();
$bookEntity = $em->getRepository('BooksBundle:Book')->find($id);
$user = $this->getUser()->getId();
$this->get('order.complete')->returnOrder($bookEntity, $user);
$quantity = $bookEntity->getQuantity();
if (!$bookEntity) {
throw $this->createNotFoundException('Unable to find Book entity.');
}
return new JsonResponse(array(
'quantity' => $quantity,
), 200);
order.complete service:
public function returnOrder(Book $bookEntity, $userId)
{
$dq = $this->entityManager->createQueryBuilder('o')
->update('BaseBundle:Order', 'o')
->set('o.status', ':status')
->where('o.book = :id')
->andWhere('o.user = :user')
->andWhere('o.status = \'active\'')
->setParameter('status', 'done')
->setParameter('id', $bookEntity)
->setParameter('user', $userId)
->setFirstResult(0)
->setMaxResults(1)
->getQuery();
$dq->execute();
$this->entityManager->getRepository('BooksBundle:Book')->updateQuantityPos($bookEntity);
}