Difference between Laravel's raw SQL functions

前端 未结 2 1343
悲哀的现实
悲哀的现实 2020-12-31 14:16

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

2条回答
  •  长发绾君心
    2020-12-31 15:01

    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;'));
    

提交回复
热议问题