Zi 字媒體
2017-07-25T20:27:27+00:00
Laravel 中的 Query Builder 是一個可以幫你組合 SQL Query 並連結資料庫的物件,底層是使用 PDO 連結資料庫。
如果沒有使用 Eloquent ORM 的話,Query Builder 也是個不錯的選擇
1.Select
// Select All
result = DB::table('genre')->get(); // 搜尋條件 + 取得第一筆 raw result = DB::table('genre')
->where('genre_name', '國語歌曲')
->where('genre_id', 28);
->first();
// Order By
result = DB::table('genre') ->orderBy('genre_id', 'DESC') ->get(); // 利用 pluck 取該欄位的值 result = DB::table('genre')
->where('genre_name', '國語歌曲')
->pluck('genre_name');
// List 該欄位的值
result = DB::table('genre')->lists('genre_name'); // value key result = DB::table('genre')->lists('genre_name', 'genre_id');
// 選擇欄位
result = DB::table('genre')->select('genre_id', 'genre_name')->get(); // 更換欄位名稱 result = DB::table('genre')->select('genre_id as id')->get();
2.Join
// Join
result = DB::table('album') ->join('song', 'song_id', '=', 'song.song_id') ->get(); // Left Join result = DB::table('album')
->leftJoin('song', 'song_id', '=', 'song.song_id')
->get();
3.Advanced Wheres
artist_name = 'Johnson'; // SELECT * FROM artist WHERE company <> 'TEST' AND (aritst_name LIKE 'Johnson%' OR artist_twname LIKE 'Johnson%') artistObj = Artist::where('company', '<>', 'TEST')
->where(function(query) use (artist_name) {
query->where('artist_name', 'LIKE', artist_name . '%')
->orWhere('artist_twname', 'LIKE', $artist_name . '%');
})
->get();
4.Aggregates
users = DB::table('users')->count(); price = DB::table('orders')->max('price');
price = DB::table('orders')->min('price'); price = DB::table('orders')->avg('price');
$total = DB::table('users')->sum('votes');
5.Insert
// Insert
DB::table('users')->insert(
array('email' => 'johnson@example.com', 'age' => 25)
);
// Insert Get ID
$id = DB::table('users')->insertGetId(
array('email' => 'johnson@example.com', 'age' => 25)
);
6.Update
// Update
DB::table('users')
->where('id', 1)
->update(array('votes' => 1));
7.Show Query String
// Order By
result = DB::table('genre') ->orderBy('genre_id', 'DESC') ->toSql(); echo result;
8.Limit
// LIMIT 1, 10
$result = DB::table('song')
->where('type', 'open')
->skip(1)
->take(10)
->get();
Categories: Laravel
分類
Android
AngularJS
Chrome
Database
MySQL
DataStructure
Editor
Vim
Firefox
Git
Hadoop
Language
Go
Java
JavaScript
jQuery
jQueryChart
Node.js
Vue
PHP
Laravel
ZendFramework
Python
Mac
Network
Cisco
DLink
Juniper
Oauth
Server
Apache
Share
Unix
FreeBSD
Linux
WebDesign
Bootstrap
CSS
HTML
Wordpress
Search
搜尋:
寫了
5860316篇文章,獲得
23313次喜歡