Laravel 查询生成器,selectRaw 或 select and raw

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50398877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:43:09  来源:igfitidea点击:

Laravel Query Builder, selectRaw or select and raw

laravellaravel-query-builder

提问by pmiranda

What's the difference between:

有什么区别:

DB::table('some_table')
->selectRaw('COUNT(*) AS result')
->get();

and:

和:

DB::select(DB::raw(" 
SELECT COUNT(*) AS result
FROM some_table"));

In the documentation https://laravel.com/docs/5.6/queriesthey advert about using raw()due SQL Injection, but it's the same with selectRaw?

在文档https://laravel.com/docs/5.6/queries 中,他们宣传使用raw()适当的 SQL 注入,但与selectRaw?

回答by Oluwatobi Samuel Omisakin

The end result of both is the same i.e but there are some difference:

两者的最终结果是相同的,但有一些区别:

The first one:

第一个:

DB::table('some_table')
    ->selectRaw('COUNT(*) AS result')
    ->get();
  • Returns a collection of PHP objects,
  • You can call collections method fluently on the result
  • It is cleaner.
  • 返回一组 PHP 对象,
  • 您可以在结果上流畅地调用集合方法
  • 它更干净。

While the second:

而第二个:

DB::select(DB::raw(" 
    SELECT COUNT(*) AS result
    FROM some_table"
));
  • Returns an arrayof Php object.
  • 返回一个Php 对象数组

Although they have similarities: the raw query string.

尽管它们有相似之处:原始查询字符串。

回答by Bogdan

Those two examples yield the same result, although with different result data types.

这两个示例产生相同的结果,尽管结果数据类型不同。

Using raw queries can indeed be an attack vector if you don't escape values used within the query (especially those coming from user input).

如果您不转义查询中使用的值(尤其是来自用户输入的值),则使用原始查询确实可以成为攻击向量。

However that can be mitigated very easily by using bindings passed as the second parameter of any raw query method, as showcased in the same documentation(selectRawaccepts 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 pageyou referenced, the second paragraph also states the following:

但是,通过使用作为任何原始查询方法的第二个参数传递的绑定可以很容易地缓解这种情况,如同一文档中所示selectRaw接受第二个参数作为绑定数组,以及来自查询构建器的其他原始方法,例如whereRaw, 等等)。实际上在您引用的文档页面的开头,第二段还说明了以下内容:

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.

Laravel 查询构建器使用 PDO 参数绑定来保护您的应用程序免受 SQL 注入攻击。无需清理作为绑定传递的字符串。

So as long as you're careful and make sure any parameters are passed as bindings and not concatenated as plain values within the raw query string you should be safe.

因此,只要您小心并确保任何参数作为绑定传递而不是作为原始查询字符串中的纯值连接,您就应该是安全的。