0

MY SQL Query: SELECT * ,COUNT(posts_id) as `view `FROM `post_view` JOIN posts ON post_view.posts_id = posts.id GROUP BY posts_id My Eloquent Laravel:

$this->model->Join('posts','post_view.posts_id', '=', 'posts.id')
          ->selectRaw('*, count(posts_id) as view')
          ->groupBy('posts_id')
          ->get();

Error when Get by Postman:

SQLSTATE[42000]: Syntax error or access violation: 1055 'databasePost.post_view.id' isn't in GROUP BY
        (SQL: select *, count(posts_id) as view from `post_view` inner join `posts` on `post_view`.`posts_id` =
        `posts`.`id` group by `posts_id`)
2
  • what have you tried ? and what variable you set in related model ? Commented Dec 7, 2019 at 7:20
  • tou have to set model for that and then you can use that model class for laravel eloquent Commented Dec 7, 2019 at 7:27

1 Answer 1

2

This error occurs because group by requiring all columns, is the speed of the query.

I think you are using a MySQL server with version 5.7.5+. Check this out: MySQL Handling of GROUP BY

Method 1:

Use ANY_VALUE to the column or disable mysql mode:ONLY_FULL_GROUP_BY.

->selectRaw('ANY_VALUE(post_view.id), ... count(posts_id) as view')
          ->groupBy('posts_id')

PS: post_view.id and posts.id both named id, select them all out that one of them will be covered.

Method 2:

edit your applications's database config file config/database.php

In mysql array, set strict => false to disable MySQL's strict mode:

'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            ...
            'strict' => false,
        ],
Sign up to request clarification or add additional context in comments.

2 Comments

Temporarily I used the method 2.
@ltt88 Using either of these methods may hide some rows. Make sure you know what you're doing when using them

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.