Laravel Eloquent ORM - 复杂的where查询

5

I have the following query:

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

然而,这种方法并不安全,容易受到SQL注入攻击。能否有人帮我把它变得更加安全,或者告诉我如何使用ORM重构它。
谢谢!
1个回答

12

这将是你原先的查询语句

$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...)确实添加了括号。 - alx

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接