在 laravel Eloquent 中可使用 DB::raw() 实现复杂查询,1. 在 select 中添加计算字段如 count;2. 用 whereRaw 配合参数绑定安全过滤数据;3. 通过 orderByRaw 按表达式排序;4. 使用 havingRaw 对聚合结果筛选;5. 注意避免 sql 注入,优先使用参数绑定确保安全。

在 Laravel 的 Eloquent 模型中,有时需要使用原生 SQL 表达式来实现复杂查询或数据库函数操作。这时可以通过 DB::raw() 来插入原始 SQL 片段,Laravel 提供了多种方式在 Eloquent 查询中安全地使用它。
1. 在 select 中使用 DB::raw()
当你需要在查询中添加数据库函数、计算字段或别名时,可以在 select 子句中使用 DB::raw()。
例如:查询用户并计算其文章数量
<pre class="brush:php;toolbar:false;">use IlluminateSupportFacadesDB; $users = User::select( 'users.id', 'users.name', DB::raw('COUNT(posts.id) as posts_count') ) ->leftJoin('posts', 'users.id', '=', 'posts.user_id') ->groupBy('users.id', 'users.name') ->get();
2. 在 where 中使用 DB::raw()
虽然不推荐在 where 条件中直接用 DB::raw() 做字段比较(容易引发 SQL 注入),但在某些场景下可以配合使用。
例如:查找创建时间在当前时间7天前的用户
<pre class="brush:php;toolbar:false;">use IlluminateSupportFacadesDB; $users = User::whereRaw('created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)') ->get();
或者使用带参数绑定的版本更安全:
<pre class="brush:php;toolbar:false;">$days = 7; $users = User::whereRaw('created_at >= DATE_SUB(NOW(), INTERVAL ? DAY)', [$days]) ->get();
3. 在 orderBy 中使用原生表达式
如果排序逻辑较复杂,比如按计算字段排序,可以用 DB::raw() 配合 orderByRaw。
例如:按用户名字母倒序排列
<pre class="brush:php;toolbar:false;">use IlluminateSupportFacadesDB; $users = User::orderByRaw('name DESC')->get();
结合函数排序,如按昵称长度排序:
<pre class="brush:php;toolbar:false;">$users = User::select('*') ->orderByRaw('CHAR_LENGTH(name) ASC') ->get();
4. 在 having、group by 等子句中使用
当使用聚合函数后需要对结果进行过滤时,havingRaw 非常有用。
例如:查找发布超过2篇文章的用户
<pre class="brush:php;toolbar:false;">use IlluminateSupportFacadesDB; $users = User::select('users.id', 'users.name', DB::raw('COUNT(posts.id) as post_count')) ->leftJoin('posts', 'users.id', '=', 'posts.user_id') ->groupBy('users.id', 'users.name') ->havingRaw('COUNT(posts.id) > ?', [2]) ->get();
5. 注意事项与安全建议
- 尽量避免拼接用户输入到 DB::raw() 中,防止 SQL 注入
- 优先使用参数绑定(如 whereRaw 第二个参数)传递动态值
- DB::raw() 只是插入原始字符串,不会自动转义内容
- 在 Eloquent 中使用原生表达式时,确保表名和字段名正确引用
基本上就这些常用方法。只要合理使用 DB::raw(),就能在保持 Eloquent 风格的同时灵活处理复杂查询需求。关键是注意安全性,避免裸字符串拼接。


