 
  Query Builder
Laravel 提供了方便易用的資料庫查詢機制,基於 PDO 參數綁定(parameter binding),保護應用程式免於 SQL資料隱碼 (SQL injection) 攻擊。Selects(查詢)
取得整個資料表
$posts = DB::table('posts')->get();
foreach ($posts as $post) {
    var_dump($post->title);
}
$post->title 為這個列的名稱為 title 欄位的值。
取得單一資料列
$post = DB::table('posts')->where('id', '=', 1)->first();
var_dump($post->title);
取得單一資料列中的單一欄位
$title = DB::table('posts')->where('id', '=', 1)->pluck('title');
var_dump($title);
取得多資料列中的單一欄位
$titles = DB::table('posts')->lists('title');
var_dump($titles);
查詢子句
$posts = DB::table('posts')->select('id', 'title')->get();
$posts = DB::table('posts')->distinct()->get();
$posts = DB::table('posts')->select('title as subject')->get();
第二行的 distinct() 會排除重覆的內容。
第三行,利用 as 可以設定別名。這時候回傳的結果中,欄位名稱 title 就被換成 subject 了。
在查詢結果中,再加入查詢
$query = DB::table('posts')->select('title');
$posts = $query->addSelect('content')->get();
where 語句
$posts = DB::table('posts')->where('id', '=', 1)->get();
如果第 2 個參數是 '=' (等於)的話,可以省略,寫成 where('id', 1)
or 多個條件:
$posts = DB::table('posts')->where('id', '=', 1)
                           ->orWhere('title', '111')
                           ->get();
SELECT * FROM posts WHERE (id = 1) or (title = '111');
between 範圍:
$posts = DB::table('posts')->whereBetween('id', [2,4])->get();
SELECT * FROM posts WHERE id BETWEEN 2 AND 4;
$posts = DB::table('posts')->whereNotBetween('id', [2,4])->get();
SELECT * FROM posts WHERE id NOT BETWEEN 2 AND 4;
In 某個(或多個)值
$posts = DB::table('posts')->whereIn('id', [1,3,5])->get();
SELECT * FROM posts WHERE id IN (1,3,5);
$posts = DB::table('posts')->whereNotIn('id', [1,3,5])->get();
SELECT * FROM posts WHERE id NOT IN (1,3,5);
Order By 排序
$posts = DB::table('posts')->orderBy('id', 'desc')->get();
SELECT * FROM posts ORDER BY id DESC;
Group By 群組及 Having 條件
$posts = DB::table('posts')->groupBy('tag')->having('words','>', 100)->get();
having 功能和 where 相同,只是 having 可以用在運算結果(這裡指群組化,有時候可能會是加總之類的)之後,而 where 不能。
等效 SQL:
SELECT * FROM posts GROUP BY tag HAVING words > 100;
Offset & Limit
$posts = DB::table('posts')->skip(5)->take(3)->get();
你也可以指定只取一筆:
$posts = DB::table('posts')->take(1)->get();
Joins 結合資料表
基本結合
假設我們有一個資料表 comments,儲存讀者的回應,它有一個欄位 post_id 用來儲存對應的文章 id。現在,我們可以結合這兩張表:
$posts = DB::table('posts')
                ->join('comments', 'posts.id', '=', 'comments.post_id')
                ->select('posts.id', 'posts.title', 'comments.content')
                ->get();
利用 posts.id、comments.post_id 等,這種明確指定的方式來指定要比對的是哪個資料表的哪個欄位。
等效 SQL:
SELECT posts.id, posts.title, comments.content FROM posts, comments WHERE posts.id = comments.post_id;
LEFT JOIN 左外部連接
$posts = DB::table('posts')
                ->leftJoin('comments', 'posts.id', '=', 'comments.post_id')
                ->select('posts.id', 'posts.title', 'comments.content')
                ->get();
SELECT posts.id, posts.title, comments.content FROM posts LEFT JOIN comments ON posts.id = comments.post_id;
進階 Where 條件
$posts = DB::table('posts')
                ->where('title', '=', '111')
                ->orWhere(function($query)
                    {
                        $query->where('words', '>', 100)
                              ->where('tag', '=', 'php');
                    })
                ->get();
等效 SQL:
SELECT * FROM posts WHERE title = '111' or (words > 100 and tag = 'php');
Aggregates 集合方法(函數)
這裡列出使用方式及等效 SQL://計算資料筆(列)數
$postCount = DB::table('posts')->count();
//SELECT count(*) FROM posts;
//取 words 欄位最大值
$maxWords = DB::table('posts')->max('words');
//SELECT max(words) FROM posts;
//取 words 欄位最小值
$minWords = DB::table('posts')->min('words');
//SELECT min(words) FROM posts;
//計算 words 欄位平均值
$avgWords = DB::table('posts')->avg('words');
//SELECT avg(words) FROM posts;
//計算 words 欄位總計值
$sumWords = DB::table('posts')->sum('words');
//SELECT sum(words) FROM posts;
Raw Expressions 原生表達式
有時候你會需要使用原生 SQL 來查詢,可以使用 DB::raw 方法達成。要注意的是,你所撰寫的原生 SQL 是一段字串,因此必須小心 SQL 隱碼(SQL injection)攻擊。
$posts = DB::table('posts')
                ->select(DB::raw('count(*) as post_count'))
                ->get();
SELECT count(*) as post_count FROM posts;
Inserts (新增)
DB::table('posts')->insert(
    ['title'=>'Hello!', 'content'=>'Laravel Demo~']
);
等效 SQL:
INSERT INTO posts (title, content) VALUES ('Hello!', 'Laravel Demo~');
$id = DB::table('posts')->insertGetId(
    ['title'=>'Hello 2!', 'content'=>'Laravel Demo~']
);
var_dump($id);
如果要一次新增多筆資料:
DB::table('posts')->insert([
    ['title'=>'Hello! 1', 'content'=>'Laravel Demo~'],
    ['title'=>'Hello! 2', 'content'=>'Laravel Demo~'],
    ['title'=>'Hello! 3', 'content'=>'Laravel Demo~']
]);
Updates (更新)
DB::table('posts')
        ->where('id', 1)
        ->update(['title'=>'Hi!']);
UPDATE posts SET title = 'Hi!' WHERE id = 1;
DB::table('posts')->increment('words');
DB::table('posts')->increment('words', 10);
DB::table('posts')->decrement('words');
DB::table('posts')->decrement('words', 10);
等效 SQL:
UPDATE posts SET words = words + 1;
UPDATE posts SET words = words + 10;
UPDATE posts SET words = words - 1;
UPDATE posts SET words = words - 10;
DB::table('posts')
        ->where('id',1)
        ->increment('words', 1);
UPDATE posts SET words = words + 1 WHERE id = 1;
Deletes (刪除)
DB::table('posts')
        ->where('words', '>', 200)
        ->delete();
DELETE FROM posts WHERE words > 200;
DB::table('posts')->delete();
DELETE FROM posts;
也可以使用清除整個資料表的方法:
DB::table('posts')->truncate();
TRUNCATE TABLE posts;
      本文網址:http://blog.tonycube.com/2015/01/laravel-15-query-builder.html
由 Tony Blog 撰寫,請勿全文複製,轉載時請註明出處及連結,謝謝 😀
由 Tony Blog 撰寫,請勿全文複製,轉載時請註明出處及連結,謝謝 😀
 
 
作者已經移除這則留言。
回覆刪除您好,首先謝謝您的系列教學讓我收穫很多!
回覆刪除有些問題想請教一下,我目前使用最新版的laravel,安裝 VS Code、Mac OS
Laravels內大部分的函數都可以透過cmd + 滑鼠右鍵連到原始檔看程式碼,唯獨DB操作相關的皆無法連到原始檔看程式碼? 我有試過使用 PHPStorm也有一樣的問題。
舉例來說:
DB::insert(.......); 我想查看DB和 insert的原始碼、函數的用途、要放哪些參數,完全看不到。
XXModel::orderBy(......)->get(); 我想查看orderBy, get的原始碼和函數的用途、參數,也是都看不到。
請問您有遇過這個問題嗎?一直google不到相關資訊
謝謝