一、ORM簡介
ORM(Object Relational Mapping)即對象關係映射,它把關係資料庫映射成對象導向的編程語言里,從而在編程語言中使用資料庫,實現代碼對象與資料庫表的映射。ORM技術的優勢在於,通過面向對象的方式處理數據,避免了通過SQL語句操作資料庫導致的性能問題、可維護性問題。
二、Laravel中的ORM
Laravel是一個PHP框架,它的ORM層提供了完整而強大的資料庫查詢和操作API,可以輕鬆地在Laravel中使用ORM實現與資料庫的交互。在Laravel中,ORM採用了流式的語法,可以靈活組合查詢條件和查詢類型,同時還支持原始的SQL語句。
三、Laravel ORM SQL語句輸出方法
Laravel ORM提供了多種方法輸出SQL語句,便於開發者在測試或Debug的時候查看查詢語句的執行情況。下面介紹幾種常用的輸出SQL語句的方法:
1. toSql()
<?php
$query = DB::table('users')
->select('name', 'email')
->where('votes', '>', 100);
$sql = $query->toSql();
?>
toSql()方法可以將構建的查詢語句轉化為字元串形式輸出,便於開發者查看構建的SQL語句是否正確:
<?php
var_dump($sql);
//輸出結果:
string(58) "select `name`, `email` from `users` where `votes` > ?"
?>
2. dump()
dump()方法可以在控制台中列印構建的查詢SQL語句以及佔位符綁定的參數值:
<?php
$query = DB::table('users')
->select('name', 'email')
->where('votes', '>', 100);
$query->dump();
?>
執行結果如下:
select `name`, `email` from `users` where `votes` > ?
array(1) {
[0]=>
int(100)
}
3. dd()
dd()方法可以在瀏覽器中輸出構建的查詢SQL語句以及佔位符綁定的參數值:
<?php
$query = DB::table('users')
->select('name', 'email')
->where('votes', '>', 100);
dd($query);
?>
在瀏覽器中輸出的結果如下:
Illuminate\Database\Query\Builder {#3775
+connection: Illuminate\Database\MySqlConnection {#3760
...
}
+grammar: Illuminate\Database\Query\Grammars\MySqlGrammar {#3776
...
}
+processor: Illuminate\Database\Query\Processors\MySqlProcessor {#3777
...
}
+bindings: array:1 [
0 => 100
]
+aggregate: null
+columns: array:2 [
0 => "name"
1 => "email"
]
...
}
四、數據操作
Laravel ORM提供了多種數據操作的方法,包括查詢、插入、更新、刪除等操作。以查詢為例,下面介紹Laravel ORM的一些常用方法:
1. select()
select()方法用於選擇要查詢的欄位:
<?php
$users = DB::table('users')
->select('name', 'email as user_email')
->get();
?>
get()方法用於執行查詢,執行結果返回一個集合的對象。執行結果如下:
Illuminate\Support\Collection {#3762
all: [
{#3774
+"name": "John",
+"user_email": "john@example.com",
},
{#3776
+"name": "Jane",
+"user_email": "jane@example.com",
},
],
}
2. where()
where()方法用於設置查詢條件:
<?php
$users = DB::table('users')
->where('name', '=', 'John')
->get();
?>
執行結果返回滿足條件的記錄集合,執行結果如下:
Illuminate\Support\Collection {#3772
all: [
{#3769
+"id": 1,
+"name": "John",
+"email": "john@example.com",
},
],
}
3. orderBy()
orderBy()方法用於設置查詢結果的排序規則:
<?php
$users = DB::table('users')
->orderBy('name', 'desc')
->get();
?>
執行結果返回根據指定欄位進行排序後的記錄集合,執行結果如下:
Illuminate\Support\Collection {#3762
all: [
{#3774
+"id": 2,
+"name": "Jane",
+"email": "jane@example.com",
},
{#3776
+"id": 1,
+"name": "John",
+"email": "john@example.com",
},
],
}
4. limit()
limit()方法用於限制查詢結果的記錄數量:
<?php
$users = DB::table('users')
->offset(1)
->limit(1)
->get();
?>
執行結果返回滿足條件的記錄集合,執行結果如下:
Illuminate\Support\Collection {#3772
all: [
{#3769
+"id": 2,
+"name": "Jane",
+"email": "jane@example.com",
},
],
}
原創文章,作者:RZMHX,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/332109.html