PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, February 10, 2022

[FIXED] Symfony doctrine orderby and group by (distinct)

 February 10, 2022     doctrine-orm, mysql, orm, sql, symfony     No comments   

Issue

I am trying to get the latest booked courses (unique). I have tried the following with the Doctrine querybuilder:

$repository = $this->getDoctrine()->getRepository('AppBundle:Booking');

$query = $repository->createQueryBuilder('b')
->select('(b.course) AS course')
->orderBy('b.id', 'DESC')
->groupBy('b.course')
->setMaxResults(5)
->getQuery();

Without the orderby it works but it will traverse the bookings ascending. I need the latest booked courses. With this query I am getting this error:

SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column ... which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by 500 Internal Server Error - DriverException

I also tried the following:

$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
   'SELECT DISTINCT c.id
    FROM AppBundle:Booking b
    JOIN b.course c
    ORDER BY b.id DESC'
);

SQLSTATE[HY000]: General error: 3065 Expression #1 of ORDER BY clause is not in SELECT list, references column ... which is not in SELECT list; this is incompatible with DISTINCT

Now I have searched for solutions and basically found a lot of suggestions to disable ONLY_FULL_GROUP_BY. Disable ONLY_FULL_GROUP_BY

Some comments state there that it is not wise to do that in order to comply to sql standards. Then how is this possible in a way that does work?


Solution

You could try this way:

$query = $repository->createQueryBuilder('b')
->select('(b.course) AS course')
->leftJoin('AppBundle:Booking', 'b2', 'WITH', 'b.course = b2.course AND b.id < b2.id')
->where('b2.id IS NULL')
->orderBy('b.id', 'DESC')
->setMaxResults(5)
->getQuery();

You'll get only the bookings with greatest id for every course, so no need for grouping by course.



Answered By - sast
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing