Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

php - Difference between Laravel's raw SQL functions

It seems I'm not the only person struggling with the differences between Laravel's DB::raw(), DB::select(), DB::statement(), and DB::unprepared() methods. It seems as if one almost needs to try a given SQL statement with all 4 to identify which will work. Can anybody clarify how they relate to each other, and which to use for what purposes?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I will try to clarify:

DB::raw()

It generates a raw and sanitized SQL string, to be passed to other query/statements, preventing SQL injections. Is to be used with all of the and never alone. And you should never send a not sanitized string to your query/statements.

DB::select(DB::raw('select * from whatever'));

DB::select()

Is for simple selects:

DB::select(DB::raw('select * from whatever'));

DB::statement()

I think it work with selects, but should be used for non SQL query commands:

DB::statement(DB::raw('update whatever set valid = true;'));

DB::unprepared()

All SQL commands in Laravel are prepared by default, but sometimes you need to execute a command in an unprepared mode, because some commands in some database cannot be ran in prepared mode. Here's an issue I opened about this: https://github.com/laravel/framework/issues/53

DB::unprepared(DB::raw('update whatever set valid = true;'));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...