从零开始系列-Laravel编写api服务接口:6.数据库查询(未完待续)
简介
今天开始写点简单的内容,把开发过程中经常用到的查询列出来,想到哪里写到哪里吧。
提纲:
- 一般查询
- 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 协议》,转载必须注明作者和本文链接
推荐文章: