今天要介紹的是剩下比較常見的其他SQL寫法
<?php
// Join 要放 leftJoin, rightJoin, crossJoin都可
DB::table('users')
->join('contacts', 'users.id', '=', 'contacts.user_id')
->join('orders', 'users.id', '=', 'orders.user_id')
->select('users.*', 'contacts.phone', 'orders.price')
->get();
//聯集
use Illuminate\Support\Facades\DB;
$first = DB::table('users')
->whereNull('first_name');
$users = DB::table('users')
->whereNull('last_name')
->union($first)
->get();
//whereNull 是否為null / whereNotNull 不為null / orWhereNull 或是否為null / orWhereNotNull 或不為null
DB::table('users')
->whereNull('updated_at')
->get();
//使用日期當搜尋條件
DB::table('users')
->whereDate('created_at', '2016-12-31')
->get();
//使用時間當搜尋條件
DB::table('users')
->whereTime('created_at', '=', '11:20:45')
->get();
//用來驗證兩個欄位是否相同, 也可加上判斷式使用
DB::table('users')
->whereColumn('first_name', 'last_name')
->get();
DB::table('users')
->whereColumn([
['first_name', '=', 'last_name'],
['updated_at', '>', 'created_at'],
])->get();
//Order By 按照欄位排序
DB::table('users')
->orderBy('name', 'desc')
->orderBy('email', 'asc')
->get();
//Group By havingBetween 設定搜尋結果的範圍
DB::table('orders')
->selectRaw('count(id) as number_of_orders, customer_id')
->groupBy('customer_id')
->havingBetween('number_of_orders', [5, 15])
->get();
?>