我想将 SQL 查询转换为 Laravel eloquent

I want to convert SQL query to Laravel eloquent

我有这个 SQL 查询:

SELECT * 
FROM posts 
RIGHT JOIN files ON posts.id = files.fileable_id 
GROUP BY posts.id 
HAVING posts.user_id = 3125

有效,但我需要将其转换为 Laravel eloquent 我试过此代码

 $postsHaveFileCount = DB::table('posts')
                     ->rightJoin('files', 'posts.id', '=', 'files.fileable_id')
                     ->groupBy('posts.id')
                     ->having('posts.user_id', '=', $user->id)
                     ->get()->count();
  echo $postsHaveFileCount;

但是我有这个错误

(2/2) QueryException SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #17 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'staff.files.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by (SQL: select * from posts right join files on posts.id = files.fileable_id group by posts.id having posts.user_id = 3125)

我将感谢所有帮助我解决问题的人,在此先感谢。

试试这个。 将以下语句复制并粘贴到您的代码中,然后 运行 它。

SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));

由于您使用的是 group by,因此您必须仅设置在 'select' 部分的 group by 语句中使用的列。如果您未在 'select' 处使用任何值,Laravel 将自动选择所有出现上述错误的列。检查下面修改后的代码

    $postsHaveFileCount = DB::table('posts')
                    ->select('posts.id')
                    ->rightJoin('files', 'posts.id', '=', 'files.fileable_id')
                    ->groupBy('posts.id', 'posts.user_id')
                    ->having('posts.user_id', '=', $user->id)
                    ->get()->count();
    echo $postsHaveFileCount;

就运行

$ sudo mysql -u root -p

为您的 MySQL 服务器实例更改 SQL 模式

mysql > SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));

另一种方法是使用 mysql 配置 转到/etc/mysql/my.cnf

**add a section for [mysqld] and right below it add the statement sql_mode = ""
restart the mysql service $ sudo systemctl restart mysql**