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

在 Laravel 的 Eloquent 模型中,有时需要使用原生 SQL 表达式来实现复杂查询或数据库函数操作。这时可以通过 DB::raw() 来插入原始 SQL 片段,Laravel 提供了多种方式在 Eloquent 查询中安全地使用它。
例如:查询用户并计算其文章数量
<pre class="brush:php;toolbar:false;">use Illuminate\Support\Facades\DB;
$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();
例如:查找创建时间在当前时间7天前的用户
<pre class="brush:php;toolbar:false;">use Illuminate\Support\Facades\DB;
$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();
例如:按用户名字母倒序排列
<pre class="brush:php;toolbar:false;">use Illuminate\Support\Facades\DB;
$users = User::orderByRaw('name DESC')->get();
结合函数排序,如按昵称长度排序:
<pre class="brush:php;toolbar:false;">$users = User::select('*')
             ->orderByRaw('CHAR_LENGTH(name) ASC')
             ->get();
例如:查找发布超过2篇文章的用户
<pre class="brush:php;toolbar:false;">use Illuminate\Support\Facades\DB;
$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();
基本上就这些常用方法。只要合理使用 DB::raw(),就能在保持 Eloquent 风格的同时灵活处理复杂查询需求。关键是注意安全性,避免裸字符串拼接。
以上就是laravel怎么在 Eloquent 中使用 DB::raw() 执行原生表达式_laravel Eloquent DB::raw原生表达式使用方法的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                 
                                
                                 收藏
收藏
                                                                             
                                
                                 收藏
收藏
                                                                             
                                
                                 收藏
收藏
                                                                            Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号