search
尋找貓咪~QQ 地點 桃園市桃園區 Taoyuan , Taoyuan

[Laravel]Query Builder

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' => '[email protected]', 'age' => 25)
);

// Insert Get ID
$id = DB::table('users')->insertGetId(
    array('email' => '[email protected]', '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



熱門推薦

本文由 blogjohnsonluorg 提供 原文連結

寵物協尋 相信 終究能找到回家的路
寫了7763篇文章,獲得2次喜歡
留言回覆
回覆
精彩推薦