Laravel支持使用原生SQL查詢,但應(yīng)優(yōu)先使用參數(shù)綁定以確保安全;1. 使用DB::select()執(zhí)行帶參數(shù)綁定的SELECT查詢,防止SQL注入;2. 使用DB::update()執(zhí)行UPDATE操作並返回影響行數(shù);3. 使用DB::insert()插入數(shù)據(jù);4. 使用DB::delete()刪除數(shù)據(jù);5. 使用DB::statement()執(zhí)行如CREATE、ALTER等無(wú)結(jié)果集的SQL語(yǔ)句;6. 推薦在Query Builder中使用whereRaw、selectRaw等方法結(jié)合原生表達(dá)式以提升安全性;7. 避免使用DB::unprepared()處理用戶輸入,僅用於可信的內(nèi)部操作??傊?,原生SQL可用,但必須通過(guò)參數(shù)綁定保障安全,並優(yōu)先選擇更安全的Query Builder擴(kuò)展方法。
In Laravel, while Eloquent ORM and the Query Builder are commonly used, there are times when you need to write raw SQL queries for complex operations or performance optimization. Laravel provides several ways to execute raw SQL safely and effectively.

Here's a practical example of using raw SQL in Laravel:
? Using DB::select()
for Raw SELECT Queries
use Illuminate\Support\Facades\DB; $users = DB::select('SELECT * FROM users WHERE age > ?', [18]);
- The first parameter is the raw SQL.
- The second is an array of bindings (to prevent SQL injection).
- Returns an array of
stdClass
objects.
? Note: Always use parameter binding (the
[18]
) instead of concatenating variables directly.
? Using DB::update()
for Raw UPDATE Queries
$affected = DB::update('UPDATE users SET votes = ? WHERE name = ?', [100, 'John']);
- Returns the number of affected rows.
? Using DB::insert()
for Raw INSERT Queries
DB::insert('INSERT INTO users (name, email, age) VALUES (?, ?, ?)', [ 'Jane Doe', 'jane@example.com', 25 ]);
? Using DB::delete()
for Raw DELETE Queries
$deleted = DB::delete('DELETE FROM users WHERE age < ?', [18]);
? Using DB::statement()
for Schema or Non-Select Queries
Use this for raw SQL that doesn't return results (eg, CREATE
, ALTER
, DROP
):
DB::statement('CREATE TABLE IF NOT EXISTS temp_users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255))');
? Using Raw Expressions in Query Builder (Safer Alternative)
Instead of full raw queries, you can inject raw expressions where needed:

$users = DB::table('users') ->whereRaw('age > ? AND status = ?', [18, 'active']) ->selectRaw('id, name, updated_at, (age * 2) as doubled_age') ->get();
Or order by a raw expression:
->orderByRaw('name ASC, created_at DESC')
? Using DB::unprepared()
(Not Recommended)
This runs raw SQL without any binding — dangerous if user input is involved .
DB::unprepared('DROP TABLE users_backup');
?? Only use for trusted internal operations (eg, migrations, setup scripts).
Summary of Common Methods
Method | Use Case |
---|---|
DB::select()
|
Raw SELECT queries |
DB::update()
|
Raw UPDATE queries |
DB::insert()
|
Raw INSERT queries |
DB::delete()
|
Raw DELETE queries |
DB::statement()
|
Schema or DDL queries |
DB::unprepared()
|
Unsafe — avoid with dynamic input |
If you're working inside Eloquent models or need more flexibility, consider using raw expressions ( whereRaw
, selectRaw
, etc.) instead of full raw queries — they're safer and integrate better with Laravel's ecosystem.
Basically, raw SQL is supported, but always prioritize parameter binding and avoid unprepared
with user data.
以上是Laravel Raw SQL查詢示例的詳細(xì)內(nèi)容。更多資訊請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

熱AI工具

Undress AI Tool
免費(fèi)脫衣圖片

Undresser.AI Undress
人工智慧驅(qū)動(dòng)的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費(fèi)的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費(fèi)的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強(qiáng)大的PHP整合開(kāi)發(fā)環(huán)境

Dreamweaver CS6
視覺(jué)化網(wǎng)頁(yè)開(kāi)發(fā)工具

SublimeText3 Mac版
神級(jí)程式碼編輯軟體(SublimeText3)

usearestapitobridgephpandmlmodelsbyrunningthemodelinpythonviaflaskorfastapiandcallingitfromphpusingcurlorguzzle.2.runpythonscriptsdirectsdirectlyectlyectlyfromphpsingexec()orshell_exec()orshell_exec()orshell_exec()

Laravel支持使用原生SQL查詢,但應(yīng)優(yōu)先使用參數(shù)綁定以確保安全;1.使用DB::select()執(zhí)行帶參數(shù)綁定的SELECT查詢,防止SQL注入;2.使用DB::update()執(zhí)行UPDATE操作並返回影響行數(shù);3.使用DB::insert()插入數(shù)據(jù);4.使用DB::delete()刪除數(shù)據(jù);5.使用DB::statement()執(zhí)行如CREATE、ALTER等無(wú)結(jié)果集的SQL語(yǔ)句;6.推薦在QueryBuilder中使用whereRaw、selectRaw等方法結(jié)合原生表達(dá)式以提升安

響應(yīng)式編程在Java中通過(guò)ProjectReactor和SpringWebFlux實(shí)現(xiàn)高並發(fā)、低延遲的非阻塞服務(wù)。 1.ProjectReactor提供Mono和Flux兩個(gè)核心類型,支持聲明式處理異步數(shù)據(jù)流,並通過(guò)操作符鏈進(jìn)行轉(zhuǎn)換、過(guò)濾等操作;2.SpringWebFlux基於Reactor構(gòu)建,支持註解式和函數(shù)式兩種編程模型,運(yùn)行在Netty等非阻塞服務(wù)器上,可高效處理大量並發(fā)連接;3.使用WebFlux Reactor能提升I/O密集型場(chǎng)景下的並發(fā)能力與資源利用率,天然支持SSE、WebSo

JWT是一種用於安全傳輸信息的開(kāi)放標(biāo)準(zhǔn),在Java中可通過(guò)JJWT庫(kù)實(shí)現(xiàn)認(rèn)證與授權(quán),1.添加JJWT的API、Impl和Jackson依賴;2.創(chuàng)建JwtUtil工具類生成、解析和驗(yàn)證Token;3.編寫(xiě)JwtFilter攔截請(qǐng)求併校驗(yàn)Authorization頭中的BearerToken;4.在SpringBoot中註冊(cè)Filter保護(hù)指定路徑;5.提供登錄接口在驗(yàn)證用戶後返回JWT;6.受保護(hù)接口通過(guò)解析Token獲取用戶身份和角色進(jìn)行訪問(wèn)控制,最終實(shí)現(xiàn)無(wú)狀態(tài)、可擴(kuò)展的安全機(jī)制,適合分佈式系

Go泛型從1.18開(kāi)始支持,用於編寫(xiě)類型安全的通用代碼。 1.泛型函數(shù)PrintSlice[Tany](s[]T)可打印任意類型切片,如[]int或[]string。 2.通過(guò)類型約束Number限制T為int、float等數(shù)字類型,實(shí)現(xiàn)Sum[TNumber](slice[]T)T安全求和。 3.泛型結(jié)構(gòu)體typeBox[Tany]struct{ValueT}可封裝任意類型值,配合NewBox[Tany](vT)*Box[T]構(gòu)造函數(shù)使用。 4.為Box[T]添加Set(vT)和Get()T方法,無(wú)需

table-layout:fixed會(huì)強(qiáng)製表格列寬由第一行單元格寬度決定,避免內(nèi)容影響佈局。 1.設(shè)置table-layout:fixed並指定表格寬度;2.為第一行th/td設(shè)置具體列寬比例;3.配合white-space:nowrap、overflow:hidden和text-overflow:ellipsis控製文本溢出;4.適用於後臺(tái)管理、數(shù)據(jù)報(bào)表等需穩(wěn)定佈局和高性能渲染的場(chǎng)景,能有效防止佈局抖動(dòng)並提升渲染效率。

使用JUnit5和Mockito能有效隔離依賴進(jìn)行單元測(cè)試,1.通過(guò)@Mock創(chuàng)建模擬對(duì)象,@InjectMocks注入被測(cè)實(shí)例,@ExtendWith啟用Mockito擴(kuò)展;2.使用when().thenReturn()定義模擬行為,verify()驗(yàn)證方法調(diào)用次數(shù)與參數(shù);3.可模擬異常場(chǎng)景並驗(yàn)證錯(cuò)誤處理;4.推薦構(gòu)造函數(shù)注入、避免過(guò)度模擬、保持測(cè)試原子性;5.使用assertAll()合併斷言,@Nested組織測(cè)試場(chǎng)景,從而提升測(cè)試可維護(hù)性和可靠性。

Choosetheappropriateindextypebasedonusecase,suchassinglefield,compound,multikey,text,geospatial,orTTLindexes.2.ApplytheESRrulewhencreatingcompoundindexesbyorderingfieldsasequality,sort,thenrange.3.Designindexestosupportcoveredqueriesbyincludingallque
