Using GROUP_BY with a query builder and mySQL >= 5.7

I’m using a symfony web app and have created a bundle to fetch a legacy WordPress database and it used to work fine with this:

class PostsProvider extends AbstractProvider
{
    // ...

    public function searchPostsWith($queries, $locale)
    {
        // "p" stands for Posts class 
        $qb = $this->repPost->createQueryBuilder('p');

        $qb
            ->select('p.id')
            ->addSelect('p.postTitle as title')
            ->addSelect('p.postContent as content')
            ->addSelect('p.postType as type')
            ->addSelect('p.postName as slug')
                ->where('p.postStatus = :publish')
                ->andWhere('p.postType = :post')
                ->orWhere('p.postType = :page')
                    ->setParameter('publish', 'publish')
                    ->setParameter('post', 'post')
                    ->setParameter('page', 'page')
            ->leftJoin('WordPressBundle:TermRelationships', 'r', 'HAVING', 'p.id = r.objectId')
            ->innerJoin('WordPressBundle:Terms', 't', 'WITH', 'r.termTaxonomyId = t.termId')
            ->addSelect('t.slug as locale')
                ->having('t.slug = :locale')
                ->setParameter('locale', $locale)
            ;
        // ...

But since I upgraded to mySQL 5.7 on my local environment I got:

Read More

SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #6 of SELECT list is not in GROUP BY clause and contains nonaggregated column ‘(db_name).a1_.slug’ which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

So I tried to add the following:

->leftJoin('WordPressBundle:TermRelationships', 'r', 'HAVING', 'p.id = r.objectId')
    ->groupBy('p.id')
->innerJoin('WordPressBundle:Terms', 't', 'WITH', 'r.termTaxonomyId = t.termId')
    ->groupBy('r.termTaxonomyId')

But that did not help.

The mySQL docs recommends to change the mode or add a group by clause but I would prefer to not change the configuration.

Any suggestion on the best way to adapt my code to get rid of this error with a background compatibility ?

Thanks.

Related posts

1 comment

  1. Maybe, after your upgrade to 5.7, the default sql_mode is changed.

    You may check the old sql_mode and set it the same for 5.7.

    Actually, you can easily change it using SQL:

    set global sql_mode = '';
    

Comments are closed.