【问题标题】:Laravel Eloquent ORM - Complex where queriesLaravel Eloquent ORM - 复杂的 where 查询
【发布时间】:2015-05-16 05:08:19
【问题描述】:

我有以下疑问:

DB::select("SELECT * FROM mod_dns_records WHERE (scheduled = 'N' AND scheduleTime = 0 AND domainId = {$id}) OR (deleteRow = 'Y' AND domainId = {$id})");

但是,这对 SQL 注入并不安全。有人可以帮我确保这个安全,或者告诉我如何用 ORM 重建它。

谢谢!

【问题讨论】:

    标签: php database laravel orm where


    【解决方案1】:

    这将是您的查询

    $result = DB::table('mod_dns_records')
                ->where('scheduled', 'N')
                ->where('scheduleTime', 0)
                ->where('domainId', $id)
                ->orWhere('deleteRow', 'Y')
                ->where('domainId', $id)
                ->get();
    

    但是我注意到它可以稍微优化一下,因为domainId 条件在两个组中都存在:

    $result = DB::table('mod_dns_records')
                ->where('domainId', $id)
                ->where(function($q){
                    $q->where('scheduled', 'N');
                    $q->where('scheduleTime', 0);
                    $q->orWhere('deleteRow', 'Y');
                })
                ->get();
    

    【讨论】:

    • 请注意,第一个示例之所以有效,是因为 OR 的优先级低于 AND ——它不会像原始查询那样添加任何分组括号。另一方面,第二个示例中的 where(...callback...) 确实添加了括号。
    猜你喜欢
    • 2015-12-06
    • 2016-06-13
    • 1970-01-01
    • 2021-11-16
    • 2014-08-18
    • 2021-02-02
    • 2014-08-19
    • 2015-01-21
    • 1970-01-01
    相关资源
    最近更新 更多