【问题标题】:I want to convert SQL query to Laravel eloquent我想将 SQL 查询转换为 Laravel eloquent
【发布时间】:2019-03-02 04:48:58
【问题描述】:

我有这个 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]: 语法错误或访问 违规:1055 SELECT 列表的表达式 #17 不在 GROUP BY 中 子句并包含非聚合列“staff.files.id” 功能上依赖于 GROUP BY 子句中的列;这是 不兼容 sql_mode=only_full_group_by (SQL: select * from posts 右加入 filesposts.id = files.fileable_id 分组posts.idposts.user_id = 3125)

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

【问题讨论】:

  • 您决定转换此应用时是否更改了您使用的 MySQL 版本?

标签: php mysql laravel eloquent laravel-5.6


【解决方案1】:

只需运行

$ 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**

【讨论】:

    【解决方案2】:

    由于您使用的是 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;
    

    【讨论】:

    • 谢谢它可以工作,但是如果我想编辑 eloquent 来应用 rightjoin 并在下面的 sql 查询中 SELECT * FROM posts RIGHT JOIN files ON posts.id = files.fileable_id AND files.fileable_type = 'App\\Post' GROUP BY posts.id HAVING posts.user_id = 3125 我试过这段代码,但它不起作用
    • 您不能在 Join 语句中使用 AND 条件。改用 Where 子句
    • 非常感谢在哪里可以工作,感谢您的帮助我的朋友
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-12-29
      • 2020-10-03
      • 1970-01-01
      • 2015-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多