Laravel 查询生成器,select原始或 select 和原始
Laravel Query Builder, selectRaw or select and raw
有什么区别:
DB::table('some_table')
->selectRaw('COUNT(*) AS result')
->get();
和:
DB::select(DB::raw("
SELECT COUNT(*) AS result
FROM some_table"));
在文档 https://laravel.com/docs/5.6/queries 中,他们宣传使用 raw()
due SQL 注入,但它与 selectRaw
?
相同
这两个示例产生相同的结果,尽管结果数据类型不同。
如果您不转义查询中使用的值(尤其是那些来自用户输入的值),那么使用原始查询确实可以成为攻击向量。
然而,通过使用作为任何原始查询方法的第二个参数传递的绑定,可以很容易地缓解这种情况,如您引用的 the same documentation (selectRaw
accepts a second parameter as an array of bindings, as well as other raw methods from the Query Builder such as whereRaw
, etc). Actually at the begining of the docs page 中所示,第二段还说明了以下内容:
The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.
因此,只要您小心并确保任何参数都作为绑定传递,而不是作为原始查询字符串中的纯值连接,您就应该是安全的。
两者的最终结果是一样的,即有一些不同:
第一个:
DB::table('some_table')
->selectRaw('COUNT(*) AS result')
->get();
- Returns PHP 个对象的集合,
- 您可以根据结果流畅地调用集合方法
- 更干净了。
而第二个:
DB::select(DB::raw("
SELECT COUNT(*) AS result
FROM some_table"
));
- Returns Php 对象的 数组 。
尽管它们有相似之处:原始查询字符串。
有什么区别:
DB::table('some_table')
->selectRaw('COUNT(*) AS result')
->get();
和:
DB::select(DB::raw("
SELECT COUNT(*) AS result
FROM some_table"));
在文档 https://laravel.com/docs/5.6/queries 中,他们宣传使用 raw()
due SQL 注入,但它与 selectRaw
?
这两个示例产生相同的结果,尽管结果数据类型不同。
如果您不转义查询中使用的值(尤其是那些来自用户输入的值),那么使用原始查询确实可以成为攻击向量。
然而,通过使用作为任何原始查询方法的第二个参数传递的绑定,可以很容易地缓解这种情况,如您引用的 the same documentation (selectRaw
accepts a second parameter as an array of bindings, as well as other raw methods from the Query Builder such as whereRaw
, etc). Actually at the begining of the docs page 中所示,第二段还说明了以下内容:
The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.
因此,只要您小心并确保任何参数都作为绑定传递,而不是作为原始查询字符串中的纯值连接,您就应该是安全的。
两者的最终结果是一样的,即有一些不同:
第一个:
DB::table('some_table')
->selectRaw('COUNT(*) AS result')
->get();
- Returns PHP 个对象的集合,
- 您可以根据结果流畅地调用集合方法
- 更干净了。
而第二个:
DB::select(DB::raw("
SELECT COUNT(*) AS result
FROM some_table"
));
- Returns Php 对象的 数组 。
尽管它们有相似之处:原始查询字符串。