I use knppaginator for getting paginated results. When I use a LEFT JOIN statement in my query, I get the following error:
Cannot count query which selects two FROM components, cannot make distinction
The code in my controller looks like this:
public function paginationAction()
{
$em = $this->get('doctrine.orm.entity_manager');
$dql = "SELECT p.name, c.name
FROM MyBundle:Products p
LEFT JOIN MyBundle:Categories c
WITH c.id = p.categoryId";
$query = $em->createQuery($dql);
$request = $this->getRequest();
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate(
$query,
$request->query->getInt('page', 1),
10
);
$viewData['pagination'] = $pagination;
return $this->render('MyBundle:results.html.twig', $viewData);
}
How can I make the LEFT JOIN statement work? When I leave out the LEFT JOIN, everything works fine.
This question is asked before. Check out this answer: Doctrine : Pagination with left Joins
Related
how can i get the unjoined values with dql ?
The problem in this code is that i'm getting only posts that have comments ..
public function getAllPostsDQL()
{
$q = $this->getEntityManager()
->createQuery('SELECT p.type,p.date,p.urlImage,p.nom,u.nom as nomU,u.prenom as prenomU ,COUNT(co) as nb,MAX(co.date) as maxDate FROM PidevBundle:Publication p LEFT OUTER JOIN
PidevBundle:Commentaire co WITH co.idPublication=p
JOIN PidevBundle:User u WITH p.idUser=u
');
return $q->getResult();
}
Try this: (for Symfony3 syntax may need to be changed)
public function getAllPostsDQL()
{
$qb = $this->createQueryBuilder('publication');
$qb->select(array('publication.type', 'publication.date', 'publication.urlImage',
'publication.nom', 'u.nom AS nomU', 'u.prenom AS prenomU',
'COUNT(co.id) AS nb', 'MAX(co.date) AS maxDate'))
->leftJoin('p.idUser', 'u')
->leftJoin('p.idCommentaire', 'co');
return $qb->getQuery()->getResult();
}
Try something like this:
public function getAllPostsDQL()
{
$q = $this->getEntityManager()->createQuery(
'SELECT
p.type,
p.date,
p.urlImage,
p.nom,
u.nom as nomU,
u.prenom as prenomU,
COUNT(co.id) as nb,
MAX(co.date) as maxDate
FROM PidevBundle:Publication p
LEFT JOIN p.idUser u
LEFT JOIN PidevBundle:Commentaire co ON co.id = u.id
');
return $q->getResult();
}
I have finally found a solution for it , although i think it's a trash code :/
Thanks for everyone .
Code :
public function getAllPostsDQL()
{
$q = $this->getEntityManager()->createQuery(
'SELECT
p.type,
p.date,
p.urlImage,
p.nom,
u.nom as nomU,
u.prenom as prenomU,
(SELECT COUNT(co.id) FROM PidevBundle:Commentaire co WHERE co.idPublication=p) as nb,
(SELECT MAX(com.date) FROM PidevBundle:Commentaire com WHERE com.idPublication=p) as maxDate
FROM PidevBundle:Publication p
INNER JOIN p.idUser u
');
return $q->getResult();
}
Is there any way to do this. I'm getting more and more confused trying different things.
I have an entity conferences that can have a place.
Places are in a many to one relationship with city.
In my query I'm trying to retrieve the city info but can't seem to retrieve it in the same place result.
This is the query used:
$qbt = $this->_em->createQueryBuilder();
$qbt
->select('conference', 'diffusion', 'speaker', 'placediff', 'confcity')
->from('AppBundle:Conference', 'conference')
->leftJoin('conference.diffusion', 'diffusion')
->leftJoin('conference.speaker','speaker')
->leftJoin('conference.place','placediff')
->leftJoin('AppBundle:City', 'confcity', 'WITH', 'confcity.id = placediff.city');
return $qbt
->getQuery()
->setHint(\Doctrine\ORM\Query::HINT_INCLUDE_META_COLUMNS, true)
->useQueryCache(true)
->useResultCache(true, 3600)
->getArrayResult();
This is what is returns, currently have only one conference.
Would love to have the second array inside place though.
Any ideas on how to accomplish this? Much obliged ~
(UPDATE) In the meantime I switched to raw sql query but really looking for a way to do this using dql
public function rawConf()
{
$conn = $this->getEntityManager()->getConnection();
$sql = 'SELECT
c0_.id AS id,
c0_.startAt AS startat,
c0_.comment AS comment,
d1_.id AS diffusion_id,
d1_.hour AS diffusion_hour,
s2_.id AS speaker_id,
c0_.place_id AS place_id,
c0_.sponsor_id AS sponsor_id,
c0_.tour_id AS tour_id_8,
d1_.movie_id AS diffusion_movie_id,
s2_.contact_id AS speaker_contact_id,
c6_.name AS ville_name,
c6_.postal AS ville_post,
c6_.department as ville_depart
FROM
conference c0_
LEFT JOIN conference_diffusion c3_ ON c0_.id = c3_.conference_id
LEFT JOIN diffusion d1_ ON d1_.id = c3_.diffusion_id
LEFT JOIN conference_speaker c4_ ON c0_.id = c4_.conference_id
LEFT JOIN speaker s2_ ON s2_.id = c4_.speaker_id
LEFT JOIN place p5_ ON c0_.place_id = p5_.id
LEFT JOIN city c6_ ON (c6_.id = p5_.city_id)';
$stmt = $conn->prepare($sql);
$stmt->execute();
return $stmt->fetchAll();
}
You should get "city" from "place" as "$city" is a property of Place entity. Try this simplified query to see it works:
$qbt = $this->_em->createQueryBuilder();
$qbt
->select('conference')
->addSelect('place')
->addSelect('city')
->from('AppBundle:Conference', 'conference')
->innerJoin('conference.place', 'place')
->innerJoin('place.city', 'city')
;
And if it works - you could easily add more joins if you need.
I am really new at Symfony and I am trying to get used to query builder. At the moment I am trying to join three tables and the following MySQL query gives me the results I need when I run it in PhpMyAdmin
SELECT * FROM pe_users u
LEFT JOIN pe_apply a ON u.id = a.user
LEFT JOIN pe_offer o ON a.id = o.application
However when I move this inside a Symfony Repository method
namespace Ache\AdminBundle\Repository;
use Doctrine\ORM\EntityRepository;
class AdminRepository extends EntityRepository{
public function findAllAppByStatus(){
$query = $this->getEntityManager()->createQuery(
'SELECT * FROM pe_users u
LEFT JOIN pe_apply a ON u.id = a.user
LEFT JOIN pe_offer o ON a.id = o.application
');
try {
return $query->getSingleResult();
} catch (\Doctrine\ORM\NoResultException $e) {
return null;
}
}
}
I get the error
[Syntax Error] line 0, col 7: Error: Expected IdentificationVariable |
ScalarExpression | AggregateExpression | FunctionDeclaration |
PartialObjectExpression | "(" Subselect ")" | CaseExpression, got '*'
What does this error mean? what am I doing wrong?
UPDATE
The three entities I have are as following
UserBundle:User
CoreBundle:Apply
AdminBundle:Offer
User.id links with Apply.user and Offer.application links with Apply.id
You can still use raw sql with Symfony if you are comfortable with that
$conn = $this->getEntityManager()->getConnection();
$sql = "SELECT * FROM pe_users u LEFT JOIN pe_apply a ON u.id = a.user LEFT JOIN pe_offer o ON a.id = o.application WHERE u.id = a.user";
$stmt = $conn->prepare($sql);
$stmt->execute();
return $stmt->fetchAll();
I would do :
public function findAllAppByStatus(){
$qb = $this->createQueryBuilder('u')
->leftJoin('CoreBundle:Apply', 'a', 'WITH', 'a.user = u')
->leftJoin('AdminBundle:Offer', 'o', 'WITH', 'o.application = a')
->setMaxResults(1); // if you return only 1 result, you want to be sure only one (or none) result is fetched
return $qb->getQuery()->getOneOrNullResult();
if you want to return possibly many results, as the 'All' in the method name suggests, get rid of the ->setMaxResults() and use $qb->getQuery()->getResult();
see how the queryBuilder works with objects, not tables. Joins are built on entities and properties, not tables and field names.
I have run into an issue in Doctrine. I have built the following query with queryBuilder
$qb = $query = $this->repoLibrary->createQueryBuilder('l');
$query = $qb
->innerJoin('l.productVariant', 'v')
->innerJoin('v.product', 'p')
->innerJoin('p.taxons', 't', 'WITH', 't.id IN (:array)')
->where('l.user = :user')
->groupBy('l.id HAVING count(DISTINCT t.id) >= :count')
->setParameter('user', $user)
->setParameter('array', $s)
->setParameter('count', count($taxons))
->getQuery();
Here is the query that is logged prior to execution:
SELECT s0_.id AS id0, s0_.consumed_at AS consumed_at1, s0_.created_at AS created_at2, s0_.updated_at AS updated_at3, s0_.user_id AS user_id4, s0_.variant_id AS variant_id5
FROM src_library s0_
INNER JOIN src_variant s1_ ON s0_.variant_id = s1_.id
INNER JOIN src_product s2_ ON s1_.product_id = s2_.id
INNER JOIN src_taxon_product s4_
ON s2_.id = s4_.product_id
INNER JOIN src_taxon s3_ ON s3_.id = s4_.taxon_id
AND (s3_.id IN (1,4))
WHERE s0_.user_id = 1
GROUP BY s0_.id HAVING count(DISTINCT s3_.id) = ? ["1,4",1,2]
When I execute this query (after inserting the parameters seen above) directly in MySQL it works perfectly, returning the 2 results that I'm looking for.
However, when it is executed by Doctrine it returns an empty array.
Any Ideas??
After scouring the interwebs I found the following answer. The problem is with the 'IN' clause. As articulated here:
https://groups.google.com/forum/#!topic/doctrine-dev/-_cINyk2dvs
My problem was being caused by the fact that I was building the 'IN' array as a string.
$s = "1,4"
instead of
$s = array(1,4);
This made all the difference in the world, and also made me feel like a n00b.
Your code looks fine and should work. I can't see your whole code but I'm guessing that it is returning an empty array because you have not actually executed the prepared sql statement yet. You should call the "getResult()" to do this.
Try this:
$qb = $query = $this->repoLibrary->createQueryBuilder('l');
$query = $qb
->select('l, v.id, p.id')
->innerJoin('l.productVariant', 'v')
->innerJoin('v.product', 'p')
->innerJoin('p.taxons', 't', 'WITH', 't.id IN (:array)')
->where('l.user = :user')
->groupBy('l.id HAVING count(DISTINCT t.id) >= :count')
->setParameter('user', $user)
->setParameter('array', $s)
->setParameter('count', count($taxons))
->getQuery()
->getResult();
I need to delete all rows where the image_id = x applies
like this
DELETE FROM `ImageVoters` WHERE image_id =1
How do I do this using DQL?
Since im trying to delete several rows at once the remove() function won't work
EntityManager#remove() expects parameter 1 to be an entity object, array given.
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery('SELECT u FROM GabrielUploadBundle:ImageVoters u WHERE u.image_id = 1');
$db_imageactions = $query->getResult();
$em->remove($db_imageactions);
$em->flush();
This is the code that works
$qb = $em->createQueryBuilder();
$qb->delete('GabrielUploadBundle:ImageVoters', 'v')
->where($qb->expr()->eq('v.image_id', ':imageId'))
->setParameter('imageId', $current_imageId);
$qb->getQuery()->execute();
You could create an ORM queryBuilder, to create a clean/safe query object by using internal orm methods
$qb->delete('My\Image\Namespace\ImageVoters', 'ivoter')
->where($qb->expr()->eq('ivoter.image_id', ':imageId')
->setParameter('imageId', 1);
$qb->getQuery()->execute();
You can also execute any raw SQL like this:
$sql = "DELETE FROM ImageVoters WHERE image_id =".$image_id;
$q = $em->getConnection()->exec($sql);