Pass Select sql to the default used in Laravel

Asked

Viewed 39 times

0

In my phpMyAdmin, I use the SQL below:

select categorias.id as categoria_id, 
nome as categoria_nome, 
count(*) as Quantidade from `livros` 
inner join `categorias` on `livros`.`categoria_id` = `categorias`.`id` group by `categoria_id`

SQL above works giving the result below:

categoria_id  categoria_nome      Quantidade
2             MEDICINA LEGAL      1
3             HISTÓRIA DO BRASIL  4
4             HISTÓRIA DO DIREITO 5
5             BIOGRAFIA           2

but when I try to pass it to Laravel 6 using the syntax below:

$dados = DB::table('livros')
            ->join('categorias', 'livros.categoria_id', '=', 'categorias.id')
            ->select(
                DB::raw('categorias.id as category_id'),
                DB::raw('nome as category_name'),
                DB::raw('count(*) as Quantidade'))
            ->groupBy('categoria_id')
            ->get();

gives error below:

Illuminate\Database\QueryException
SQLSTATE[42000]: Syntax error or access violation: 1055 'books.categorias.id' isn't in GROUP BY (SQL: select categorias.id as categoria_id, nome as categoria_name, count(*) as Quantidade from `livros` inner join `categorias` on `livros`.`categoria_id` = `categorias`.`id` group by `categoria_id`)

Where can I be wrong about that?

  • Instead of categoria_id put category.id.

  • @Virgilionovic put in groupBy ? If yes, I put and gave this: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'category.id' in 'group statement' (SQL: select categories.id as category_id, name as category_name, Count(*) as Quantity from livros Inner Join categorias on livros.categoria_id = categorias.id group by categoria.id)

1 answer

0


Solved by adding the lines below on config database.php of Laravel 6:

'mysql' => [

       'strict' => true,// acrescentado as linhas abaixo
       'modes' => [

            'STRICT_TRANS_TABLES',
            'NO_ZERO_IN_DATE',
            'NO_ZERO_DATE',
            'ERROR_FOR_DIVISION_BY_ZERO',
            'NO_AUTO_CREATE_USER',
            'NO_ENGINE_SUBSTITUTION'
        ],
 ]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.