問題描述
似乎我不是唯一一個在 Laravel 的 DB::raw()、DB::select()、DB::statement() 和 DB::unprepared() 方法之間掙扎的人.似乎幾乎需要使用所有 4 個 SQL 語句來嘗試一個給定的 SQL 語句,以確定哪個可以工作.任何人都可以澄清它們之間的關系,以及用于什么目的?
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?
推薦答案
我會盡量澄清:
它生成一個原始的和經過清理的 SQL 字符串,傳遞給其他查詢/語句,防止 SQL 注入.是與所有的和永遠不會單獨使用.并且您永遠不應該向您的查詢/語句發送未清理的字符串.
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()
用于簡單選擇:
DB::select(DB::raw('select * from whatever'));
DB::statement()
我認為它適用于選擇,但應該用于非 SQL 查詢命令:
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()
Laravel 中所有的 SQL 命令都是默認準備好的,但有時你需要在非準備模式下執行命令,因為某些數據庫中的某些命令無法在準備模式下運行.這是我打開的一個問題:https://github.com/laravel/framework/issues/53
DB::unprepared(DB::raw('update whatever set valid = true;'));
這篇關于Laravel 原始 SQL 函數的區別的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!