简体   繁体   中英

How to Convert SQL Query to Eloquent Laravel

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`)

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,
        ],

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM