I have so far 2 queries which are similar:
the first one I use when user is ROLE_REDAC
$qb = $this->createQueryBuilder('a');
$qb->LeftJoin('a.ArticlePhrases','ap')
->addSelect('ap')
->where(
$qb->expr()->andX(
$qb->expr()->eq('ap.order', '?1'),
$qb->expr()->eq('a.author', '?2')
)
)
->setParameters(//...
);
The second one when user is ROLE_ADMIN
$qb = $this->createQueryBuilder('a');
$qb->LeftJoin('a.ArticlePhrases','ap')
->addSelect('ap')
->where(
$qb->expr()->andX(
$qb->expr()->eq('ap.order', '?1')
)
)
->setParameters(...
));
There are not much difference. is it possible to call from the controller the same repository fonction and that this fonction adapt whether the actual user is ROLE_REDAC or ROLE_ADM? if yes how can I do that?
I haven't tested it, but should work
class MyCustomRepository extends EntityRepository
{
public function myCustomFunction($user_role)
{
$qb = $this->createQueryBuilder('a');
if ($user_role == 'ROLE_REDAC') {
$where_dql_expr = $qb->expr()->andX(
$qb->expr()->eq('ap.order', '?1'),
$qb->expr()->eq('a.author', '?2')
);
$qb->setParameters(//....);
}
else if ($user_role == 'ROLE_ADMIN') {
$where_dql_expr = $qb->expr()->andX(
$qb->expr()->eq('ap.order', '?1')
);
$qb->setParameters(//....);
}
$qb->LeftJoin('a.ArticlePhrases','ap')
->addSelect('ap')
->where($where_dql_expr)
->//and so on
}
}
of course into your controller you have to call it passing the right parameter
$role = //retrieve role
$custom_repo = $this->getDoctrine()
->getManager()
->getRepository('YourBundleName:MyCustomEntity');
$custom_repo->myCustomFunction($role);
Related
On my controler I get some results from database
$commandes = $em->getRepository('SWPlatformBundle:Vente')->getCommandesAFacturer($client[0]->getId());
with this SQL
public function getCommandesAFacturer($id) {
$qb = $this->createQueryBuilder('v')
->select("c.id, c.montantTTC, c.horodatageCreation, SUM(v.prixTotalVente) AS sansFrais")
->leftJoin('v.commande', 'c')
->where('c.facture IS NULL')
->andwhere('c.commercant = :commercantId')
->setParameter('commercantId', $id)
->groupBy('c.id');
return $qb
->getQuery()
->getResult();
}
And I would like to sum the sansFrais value of my request but I don't reach the sansFrais Value.
I've tried like this, but it doesn't work :
foreach($commandes as $commande){
$montantHTCollecte += $commande['sansFrais'];
}
Thanks for your help !
I am trying to right a query which return me list of the users which has uploaded video(user_id in video table ), and have paginating thingy in the query
the function is like this :
public function getUsersHasVideoShoutOut($offset, $limit)
{
$qb = $this->createQueryBuilder('u')
->Join('u.video', 'uv');
$qb->where('uv.muted=0')
->andwhere('u.muted = 0')
->addOrderBy('uv.release_date', 'DESC')
->setFirstResult($offset)
->setMaxResults($limit);
return $qb->getQuery()->getResult();
}
but the problem is that I get duplicate data in next pages , is it because of join statement and pagination in doctorine ?
You can get distinct data:
public function getUsersHasVideoShoutOut($offset, $limit)
{
$qb = $this->createQueryBuilder('u')
->Join('u.video', 'uv');
$qb->where('uv.muted=0')
->andwhere('u.muted = 0')
->addOrderBy('uv.release_date', 'DESC')
->setFirstResult($offset)
->setMaxResults($limit)
->distinct();
return $qb->getQuery()->getResult();
}
I am currently trying to build a blog website following a course that uses
Symfony 2.5.2. (PHP -v 7.0)
To retrieve a post I am using a following Controller
/**
* #Route(
* "/{slug}",
* name = "blog_post"
* )
* #Template()
*/
public function postAction($slug)
{
$PostRepo = $this->getDoctrine()->getRepository('AniaBlogBundle:Post');
$Post = $PostRepo->getPublishedPost($slug);
if(null === $Post){
throw $this->createNotFoundException('Post not found');
}
return array(
'post'=> $Post
);
}
and here is my getPublishedPost function :
public function getPublishedPost($slug){
$qb = $this->getQueryBuilder(array(
'status' => 'published'
));
$qb->andWhere('p.slug = :slug')
->setParameter('slug', $slug);
return $qb->getQuery()->getOneOrNullResult();
}
and getQueryBuilder function :
public function getQueryBuilder(array $params = array()){
$qb = $this->createQueryBuilder('p')
->select('p, c, t')
->leftJoin('p.category', 'c')
->leftJoin('p.tags', 't');
if(!empty($params['status'])){
if('published' == $params['status']){
$qb->where('p.publishedDate <= :currDate AND p.publishedDate IS NOT NULL')
->setParameter('currDate', new \DateTime());
}else if('unpublished' == $params['status']) {
$qb->where('p.publishedDate > :currDate OR p.publishedDate IS NULL')
->setParameter('currDate', new \DateTime());
}
}
if(!empty($params['orderBy'])){
$orderDir = !empty($params['orderDir']) ? $params['orderDir'] : NULL;
$qb->orderBy($params['orderBy'], $orderDir);
}
if(!empty($params['categorySlug'])){
$qb->andWhere('c.slug = :categorySlug')
->setParameter('categorySlug', $params['categorySlug']);
}
if(!empty($params['tagSlug'])){
$qb->andWhere('t.slug = :tagSlug')
->setParameter('tagSlug', $params['tagSlug']);
}
if(!empty($params['search'])) {
$searchParam = '%'.$params['search'].'%';
$qb->andWhere('p.title LIKE :searchParam OR p.content LIKE :searchParam')
->setParameter('searchParam', $searchParam);
}
return $qb;
}
}
However i get the 500 error saying : [Syntax Error] line 0, col -1: Error: Expected Literal, got end of string.
Thank you in advance for any suggestions!
I have a search bar in my page and the action in my in charge of looking for what the user search for is this :
public function searchAction(Request $request){
$em = $this->container->get('doctrine')->getEntityManager();
$evenements= $em->getRepository('Mql14mqlmeBundle:Evenement')->findAll();
if ('POST' === $request->getMethod()) {
$search = $request->get('search');
$query = $this->container->get('doctrine')->getEntityManager()->createQuery( 'SELECT e FROM Mql14mqlmeBundle:Evenement e WHERE e.nom LIKE :search')
->setParameter('search', $search);
$resultats = $query->getResult();
return $this->container->get('templating')->renderResponse('Mql14mqlmeBundle:Event:search.html.twig', array(
'resultats'=>$resultats,
));
}
return $this->listerAction();
}
It's working if the user put the exact name of some event in the database, but I want to make the search possible even if it's only a part of the name, I tried this in the query:
$query = $this->container->get('doctrine')->getEntityManager()->createQuery( 'SELECT e FROM Mql14mqlmeBundle:Evenement e WHERE e.nom LIKE :%search%')
->setParameter('search', $search);
But I'm getting this error: Invalid parameter format, : given, but :name or ?num expected.
Try to change parameter like this:
$query = $this
->container
->get('doctrine')
->getEntityManager()
->createQuery(
'SELECT e FROM Mql14mqlmeBundle:Evenement e WHERE e.nom LIKE :search'
)
->setParameter('search', '%'.$search.'%');
So in my base template, I have: {% render "EcsCrmBundle:Module:checkClock" %}
Then I created the ModuleController.php...
<?php
namespace Ecs\CrmBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Ecs\CrmBundle\Entity\TimeClock;
class ModuleController extends Controller
{
public function checkClockAction() {
$em = $this->getDoctrine()->getEntityManager();
$user = $this->get('security.context')->getToken()->getUser();
$today = time();
$start = date('Y-m-d 00:00:00');
$entities = $em->getRepository('EcsCrmBundle:TimeClock');
$query = $entities->createQueryBuilder('tc')
->select('tc.in1, tc.out1, tc.in2, tc.out2, tc.in3, tc.out3')
->where('tc.noteBy = :user')
->andWhere('tc.daydate >= :start')
->setParameter('user', $user->getid())
->setParameter('start', $start)
->setMaxResults('1')
->getQuery();
$entities = $query->getSingleResult();
if (empty($entities)) {
$ents = "clocked_out";
$this->get('session')->set('clockedin', 'clocked_out');
} else {
for ($i=1; $i <= 3; $i++) {
if ($entities["in$i"] != NULL) {
$ents = "clocked_in";
if ($i == 1) {
$this->get('session')->set('nextclock', "out$i");
} else {
$x = $i+1;
$this->get('session')->set('nextClock', "out$x");
}
if ($entities["out$i"] != NULL) {
$ents = "clocked_out";
$x = $i+1;
$this->get('session')->set('nextclock', "in$x");
}
if ($entities["out3"] != NULL) {
$ents = "day_done";
}
}
}
}
return $this->render('EcsCrmBundle:Module:topclock.html.twig', array(
'cstat' => $ents,
));
}
}
The problem is, if there is nothing in the database for the specific day for the specific user yet.. i keep getting:
An exception has been thrown during the rendering of a template ("No result was found for query although at least one row was expected.") in ::base.html.twig at line 161.
500 Internal Server Error - Twig_Error_Runtime
1 linked Exception: NoResultException ยป
I know it has something to do with the fact that is no 'result' from the database... but isn't that what i've accomplished by having the if (empty($entities)) { ?? I have no clue to fix it... any help appreciated...
Replace:
$entities = $query->getSingleResult();
With
$entity = $query->getOneOrNullResult();
If you look in Doctrine\ORM\AbstractQuery you will see that getSingleResult expects one and only one results. 0 will through an exception.
I looked at your code a bit more closely and it looks like you actually expect an array of entities. in which case use:
$entities = $query->getResult();