数据库访问类链式查询方法
一、链式查询方法
1.whereBetween()
在范围之间查询
控制器:home.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
Class Home extends Controller{
//whereBetwen在范围内查询
public function between(){
$res = DB::table('staff')->select('id','name','age')->whereBetween('age',[20,25])->get();
echo '<pre>';
print_r($res);
}
}
路由:web.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('/home/between','Home@between');
2.whereIn()
在指定数组中查询
控制器:home.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
Class Home extends Controller{
//whereIn
public function in(){
$res = DB::table('staff')->whereIn('id',[1002,1050])->get();
echo '<pre>';
print_r($res);
}
}
路由:web.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('/home/in','Home@in');
3.orWhere()
或查询
控制器:home.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
Class Home extends Controller{
//orWhere
public function whereor(){
$res = DB::table('staff')->where('id',1002)->Orwhere('id',1007)->get();
echo '<pre>';
print_r($res->toArray());
}
}
路由:web.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('/home/whereor','Home@whereor');
4.join()
多表查询
控制器:home.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
Class Home extends Controller{
//join查询
public function join(){
$res = DB::table('staff')->join('user','staff.name','=','user.name')->get();
echo '<pre>';
print_r($res);
}
}
路由:web.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('/home/join','Home@join');
二、中间件
- 定义中间件:
Mycheck.php
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Closure;
/*
中间件
固定格式
*/
class Mycheck{
public function handle(Request $request,Closure $next){
$a = 3;
$b = 5;
if($a+$b === 8){
return response('a+b='.($a+$b),200);
}
return $next($request);
}
}
- 注册中间件:
Kernel.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
protected $routeMiddleware = [
//注册中间件
'mycheck' => \App\Http\Middleware\Mycheck::class,
];
}
- 触发中间件:
web.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('/home/join','Home@join')->middleware('mycheck');