Doctrine LIMIT Syntax Error? - mysql

'[Syntax Error] line 0, col 71: Error: Expected end of string, got 'LIMIT''
Here's my code:
public function getLatestChapters()
{
return $this->_em->createQuery('SELECT c, m FROM models\Chapter c JOIN c.Manga m ORDER BY c.CreateDate LIMIT 10')->getResult();
}
What could posibly the problem for this? How can I use LIMIT in Doctrine?
I am using Doctrine 2

Seems like there is no LIMIT/OFFSET in DQL anymore.
$qb = $em->createQueryBuilder();
//.. build your query
$q = $qb->getQuery();
$q->setFirstResult($offset);
$q->setMaxResults($limit);
$result = $q->getResult();

I would Like to Contribute to this post and want to tell people that If you want to use DBAL with limit in your Unit Tests you can use following:
$client = static::createClient()
$em = $client->getContainer()->get('doctrine')->getManager();
$query = $em->createQuery('WRITE YOUR QUERY HERE');
$query->setFirstResult(0);
$query->setMaxResults(1);
$data = $query->getResult();
Same code can be used in controller also with some modifications :)

Related

symfony cannt join related tables in manytomany relationship

I cannot join tables(Products and Category) in ManyToMany relationship.
My Entities
I get this error message when I try to join them
[Syntax Error] line 0, col 511: Error: Expected Literal, got 'JOIN'
My Repository
public function GetProductsList($productid){
$fields = array['product.product','category.category']
$query = $this->getEntityManager()->createQueryBuilder()
->select($fields)
->from('TestMyBundle:product','product')
->innerJoin('TestMyBundle:category','category')
->where('product.productid=:productid')
->setParameter('productid',$productid)
->getQuery()
->getResult();
return $query;
}
Your join looks wrong and I don't see why you need an hardcoded array there. May as well just put the entity aliases directly in the select. I would write that as:
public function GetProductsList($productid){
$result = $this->getEntityManager()->createQueryBuilder()
->select('product', 'category')
->from('TestMyBundle:product','product')
->join('product.categories','category') // making an assumption your product entity has getCategories()
->where('product.productid=:productid')
->setParameter('productid',$productid)
->getQuery()
->getResult();
return $result;
}
Should work then.
Note that when you get problems like this it's useful to do something like ->getSQL() instead of getQuery() and var_dump the SQL to see what the querybuilder is producing, makes it easier to debug.

Zend Framework - join query

I build a function
public function getBannedByLogin($commentId)
{
$sql = $this->getDbAdapter()->select()
->from(array('comments' => 'comments'), array())
->join(array('users' => 'qengine_users'),
'comments.bannedBy = users.userId',
array())
->where('commentId = ?', $commentId)
;
$row = $this->fetchRow($sql);
return $row['login'];
}
And there are problems, that does'nt work! :D
Let's I explain you. Column 'bannedBy' from comments returns id of user, who give a ban. I need to join this with table users to load a login field. Where i have mistakes?
I assume the code works in the sense of not throwing an exception. If so, your code is OK, you just specifically tell Zend_Db not to select any columns.
public function getBannedByLogin($commentId)
{
$sql = $this->getDbAdapter()->select()
->from(array('comments' => 'comments'))
->join(array('users' => 'qengine_users'),
'comments.bannedBy = users.userId')
->where('commentId = ?', $commentId)
;
$row = $this->fetchRow($sql);
return $row['login'];
}
The last argument to from() and join() functions is an array of columns you wish to select. If you pass in an empty array, no columns are selected. No argument = select everything. You can, of course, specify only the columns you need too.

Doctrine Native SQL many-to-many query

I have a many-to-many relationship between Students and Programs with tables student, program, and student_program in my database.
I'm trying to join the two entities and perform some custom queries that require subqueries. This means that the Doctrine QueryBuilder cannot work because it does not support subqueries.
Instead, I'm trying the NativeSQL function and am making decent progress. However, when I try to SELECT something from the Program entity, I get the error Notice: Undefined index: Bundle\Entity\Program in vendor/doctrine/orm/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php line 180.
$mapping = new \Doctrine\ORM\Query\ResultSetMappingBuilder($em);
$mapping->addRootEntityFromClassMetadata('Student', 's');
$mapping->addJoinedEntityFromClassMetadata('Program', 'p', 's', 'programs', array('id' => 'program_id'));
// Query based on form
$sql = 'SELECT s.id, s.last_name, p.name <---- problem when this is added
FROM student s
JOIN program p
';
$query = $em->createNativeQuery($sql, $mapping);
$students = $query->getResult();
Not a direct answer but doctrine 2 does indeed support sub queries. Just create a query then feed the dql into a where class. This example is somewhat verbose but it works just fine:
public function queryGames($search)
{
// Pull params
$ages = $this->getValues($search,'ages');
$genders = $this->getValues($search,'genders');
$regions = $this->getValues($search,'regions');
$sortBy = $this->getValues($search,'sortBy',1);
$date1 = $this->getValues($search,'date1');
$date2 = $this->getValues($search,'date2');
$time1 = $this->getValues($search,'time1');
$time2 = $this->getValues($search,'time2');
$projectId = $this->getValues($search,'projectId');
// Build query
$em = $this->getEntityManager();
$qbGameId = $em->createQueryBuilder(); // ### SUB QUERY ###
$qbGameId->addSelect('distinct gameGameId.id');
$qbGameId->from('ZaysoCoreBundle:Event','gameGameId');
$qbGameId->leftJoin('gameGameId.teams', 'gameTeamGameId');
$qbGameId->leftJoin('gameTeamGameId.team','teamGameId');
if ($projectId) $qbGameId->andWhere($qbGameId->expr()->in('gameGameId.projectId',$projectId));
if ($date1) $qbGameId->andWhere($qbGameId->expr()->gte('gameGameId.date',$date1));
if ($date2) $qbGameId->andWhere($qbGameId->expr()->lte('gameGameId.date',$date2));
if ($time1) $qbGameId->andWhere($qbGameId->expr()->gte('gameGameId.time',$time1));
if ($time2) $qbGameId->andWhere($qbGameId->expr()->lte('gameGameId.time',$time2));
if ($ages) $qbGameId->andWhere($qbGameId->expr()->in('teamGameId.age', $ages));
if ($genders) $qbGameId->andWhere($qbGameId->expr()->in('teamGameId.gender',$genders));
if ($regions)
{
// $regions[] = NULL;
// $qbGameId->andWhere($qbGameId->expr()->in('teamGameId.org', $regions));
$qbGameId->andWhere($qbGameId->expr()->orX(
$qbGameId->expr()->in('teamGameId.org',$regions),
$qbGameId->expr()->isNull('teamGameId.org')
));
}
//$gameIds = $qbGameId->getQuery()->getArrayResult();
//Debug::dump($gameIds);die();
//return $gameIds;
// Games
$qbGames = $em->createQueryBuilder();
$qbGames->addSelect('game');
$qbGames->addSelect('gameTeam');
$qbGames->addSelect('team');
$qbGames->addSelect('field');
$qbGames->addSelect('gamePerson');
$qbGames->addSelect('person');
$qbGames->from('ZaysoCoreBundle:Event','game');
$qbGames->leftJoin('game.teams', 'gameTeam');
$qbGames->leftJoin('game.persons', 'gamePerson');
$qbGames->leftJoin('game.field', 'field');
$qbGames->leftJoin('gameTeam.team', 'team');
$qbGames->leftJoin('gamePerson.person', 'person');
$qbGames->andWhere($qbGames->expr()->in('game.id',$qbGameId->getDQL())); // ### THE TRICK ###
switch($sortBy)
{
case 1:
$qbGames->addOrderBy('game.date');
$qbGames->addOrderBy('game.time');
$qbGames->addOrderBy('field.key1');
break;
case 2:
$qbGames->addOrderBy('game.date');
$qbGames->addOrderBy('field.key1');
$qbGames->addOrderBy('game.time');
break;
case 3:
$qbGames->addOrderBy('game.date');
$qbGames->addOrderBy('team.age');
$qbGames->addOrderBy('game.time');
$qbGames->addOrderBy('field.key1');
break;
}
// Always get an array even if no records found
$query = $qbGames->getQuery();
$items = $query->getResult();
return $items;
}

Symfony2 - how can I get Entity Object based on custom query?

this is my custome query:
$query = $em->createQuery("SELECT max(d.id) FROM MyBundle:DBTableEntity d ");
$max_incoming_id = $query->execute();
I want it to return the Entity Object, just like this one below:
$EntityObj = $resource->getRepository("MyBundle:DBTableEntity")->findAll();
Any idea how to do that?
Something like this should work
$EntityObjects = $resource->getRepository('MyBundle:DBTableEntity')
->createQuery()
->orderBy('id', 'DESC')
->getResult();
$EntityObject = array_pop($EntityObjects);
Try This
$query = sprintf("SELECT s FROM BundleName:EntityClass s where s.field1 = %d and s.field2=%d", $field1, $field2);
$em = $this->getDoctrine()->getEntityManager();
$queryObj = $em->createQuery($query);
$entities = $queryObj->execute();
With excute you receive a array of results (entities).
so you can do $entities = $query.excute();
return $entities[0]; //this is if you have one result;
array_pop($entities) will not work this gives a error in symfony 2.6
I think you will like this style:
$EntityObj = $resource->getRepository("MyBundle:DBTableEntity")
->findOneBy(array(), array('id' => 'DESC'));
:)

"No result was found for query although at least one row was expected." Query should display records though in Symfony

I'm trying to retrieve content using two items in the URL. Here is the php/symfony code that should do it:
$em = $this->getDoctrine()->getEntityManager();
$repository = $this->getDoctrine()
->getRepository('ShoutMainBundle:Content');
$query = $repository->createQueryBuilder('p')
->where('p.slug > :slug')
->andWhere('p.subtocontentid > :parent')
->setParameters(array(
'slug' => $slug,
'parent' => $page
))
->getQuery();
$content = $query->getSingleResult();
However, when this code is executed it returns the following error:
No result was found for query although at least one row was expected.
I have done some tests, and the data held in the $slug and $page variables hold the correct information. I have also tested the MySQL query and the query brings up the desired result, which confuses me further.
Have I missed something?
As it was answered here
You are getting this error because you are using the
getSingleResult() method. it generates an Exception if it can't find
even a single result. you can use the getOneOrNullResult() instead
to get a NULL if there isn't any result from the query.
Query#getSingleResult(): Retrieves a single object. If the result
contains more than one object, an NonUniqueResultException is thrown.
If the result contains no objects, an NoResultException is thrown. The
pure/mixed distinction does not apply.
No result was found for query although at least one row was expected.
Another reason could be:
You did this
$query = $this->getEntityManager()
->createQuery('
SELECT u FROM MyBundle:User u
WHERE u.email = :email')
->setParameter('email', $email);
return $query->getSingleResult();
Instead of this
$query = $this->getEntityManager()
->createQuery('
SELECT u FROM MyBundle:User u
WHERE u.email = :email')
->setParameter('email', $email);
$query->setMaxResults(1);
return $query->getResult();
Don't you want to use "=" instead of ">" ?
If you've got this message because used
$content = $query->getSingleResult();
you can just replace it with the row below
$content = $query->getOneOrNullResult(AbstractQuery::HYDRATE_SINGLE_SCALAR) ?? 0;