database Laravel DB::insert() 和 DB::table()->insert() 的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39118995/
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
Difference between Laravel DB::insert() and DB::table()->insert()
提问by Jesper Andersen
I've been trying to figure out which one to use when, and if I should even use both.
我一直在试图弄清楚何时使用哪个,以及是否应该同时使用两者。
Been looking at Laravel docs and they have both in there. From what I can make out of it, DB::insert()
provides more "tailored" query than DB::table()->insert()
does.
一直在看 Laravel 文档,他们都在那里。据我所知,它DB::insert()
提供了更多“量身定制”的查询DB::table()->insert()
。
Would anyone be able to clarify what exactly the difference is in the two when it comes to how and when to use which?
当涉及到如何以及何时使用哪个时,有人能够澄清两者之间的确切区别吗?
回答by Bogdan Koliesnik
DB::insert()
for raw sql queries. Example:DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);
DB::table()->insert()
for query builder. Example:DB::table('users')->insert( ['email' => '[email protected]', 'votes' => 0] );
DB::insert()
对于 原始 sql 查询。例子:DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);
DB::table()->insert()
对于查询生成器。例子:DB::table('users')->insert( ['email' => '[email protected]', 'votes' => 0] );
Query builder compiles conditions to raw sql query, but I am using it because it is much more convenient.
查询生成器将条件编译为原始 sql 查询,但我使用它是因为它更方便。
回答by Yan Zhao
You always try to use query builder as much as possible, it prevents SQL injection.
您总是尽可能地尝试使用查询构建器,它可以防止 SQL 注入。
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 注入攻击。无需清理作为绑定传递的字符串
Query Builder also helps with special chars such as ', " in values. For raw statement, you need to take care of the special chars yourself.
查询生成器还可以帮助处理特殊字符,例如值中的 ', "。对于原始语句,您需要自己处理特殊字符。