簡介
今天開始寫點簡單的內容,把開發過程中經常用到的查詢列出來,想到哪裡寫到哪裡吧。
提綱:
- 一般查詢
- or 查詢
- like 查詢
- when 條件查詢
- with
- 事務
- join
- union
- 開啟日誌
- 跨庫查詢
- 分頁
1. 一般查詢
$user = User::find(1); // 查詢單個記錄
$users = User::where('status', 1)->get(); // 查詢多個記錄
$users = User::where('status', 1)->paginate(15); // page為當前頁,15 表示每頁顯示15條
$queryBuilder = User::query();
if (1==1){
$queryBuilder->where('status', 0);
}
return $queryBuilder->get();
2.or 查詢 加上and
$queryBuilder = User::query();
$queryBuilder->where('status', 1)->where(function($q)use($keywords){
$q->where('name', 'like', sprintf("%%%s%%", $keywords))
->orWhere('mobile', 'like',sprintf("%%%s%%", $keywords));
});
$user = $queryBuilder->get();
3.like 模糊查詢
$user = User::where('status', 1)
->where(function($q)user($keywords){
$q->where('name', 'like', sprintf("%%%s%%", $keyword))
->orWhere('mobile', 'like', sprintf("%%%s%%", $keyword));
})->paginate(10);
4.when 條件查詢
$user = User::when($status,function($q)use($status){
})->when($keyword,function($q)use($keywords){
$q->where('name','like',sprintf("%%%s%%", $keywords));
})->get();
5.with 查詢(一對多,一對一,防止n+1)
6.事務
7. join
8. union
9. 開啟日誌
1.在EventServiceProvider下新增
protected $listen = [
\Illuminate\Database\Events\QueryExecuted::class => [
'App\Listeners\QueryListener'
],
];
2.檔案目錄app/Listener/QueryListener.php
public function handle(QueryExecuted $event) {
$env = config('app.env');
if ($env === 'local' || $env === 'test') {
$sql = str_replace('?', "'%s'", $event->sql);
$sql = str_replace('%Y-%m-%d', "#date#", $sql); // mysql %d 表示格式化日期,vsprintf 中 %d - 包含正負號的十進位制數(負數、0、正數)
$sql_log = vsprintf($sql, $event->bindings);
$sql_log = str_replace('#date#', '%Y-%m-%d', $sql_log);
$monolog = Log::getMonolog();
$monolog->popHandler();
Log::useDailyFiles(storage_path('logs/sql.log'));
Log::info($sql_log.PHP_EOL);
}
}
或者
public function handle(QueryExecuted $event) {
$env = env('APP_ENV', 'production');
// // todo 演示期間加上日誌,隨時查問題(正式上線去掉 || $env === 'production')
if ($env === 'local') {
$sql = str_replace('?', "'%s'", $event->sql);
$sql_log = vsprintf($sql, $event->bindings);
$log = Log::channel('sqlLog');
$log->info($sql_log.PHP_EOL);
}
}
10. 跨庫查詢
1.新增垮庫配置檔案
開啟config下配置檔案database.php
新增跨庫配置(同時env檔案也同步新增響應配置):
'mysql_platform' =>[ // 跨庫,連線醫聯體的資料庫
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => env('DB_PREFIX', ''),
'strict' => true,
'engine' => null,
],
用法:
- 直接用db類
DB::connection("mysql_platform")->table('')->get();
- 對應表模型裡面
protected $connection = 'mysql_platform';
11. 分頁
分頁就不用說了,page 當前頁,per_page 每頁數DB::table('users')->paginate($per_page);
本作品採用《CC 協議》,轉載必須註明作者和本文連結