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