博客列表 >数据库访问类链式查询方法

数据库访问类链式查询方法

王佳祥
王佳祥原创
2020年09月18日 17:27:382126浏览

数据库访问类链式查询方法

一、链式查询方法

1.whereBetween()在范围之间查询

控制器:home.php

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. use Illuminate\Support\Facades\DB;
  5. Class Home extends Controller{
  6. //whereBetwen在范围内查询
  7. public function between(){
  8. $res = DB::table('staff')->select('id','name','age')->whereBetween('age',[20,25])->get();
  9. echo '<pre>';
  10. print_r($res);
  11. }
  12. }

路由:web.php

  1. <?php
  2. use Illuminate\Support\Facades\Route;
  3. Route::get('/home/between','Home@between');


2.whereIn()在指定数组中查询

控制器:home.php

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. use Illuminate\Support\Facades\DB;
  5. Class Home extends Controller{
  6. //whereIn
  7. public function in(){
  8. $res = DB::table('staff')->whereIn('id',[1002,1050])->get();
  9. echo '<pre>';
  10. print_r($res);
  11. }
  12. }

路由:web.php

  1. <?php
  2. use Illuminate\Support\Facades\Route;
  3. Route::get('/home/in','Home@in');


3.orWhere() 或查询

控制器:home.php

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. use Illuminate\Support\Facades\DB;
  5. Class Home extends Controller{
  6. //orWhere
  7. public function whereor(){
  8. $res = DB::table('staff')->where('id',1002)->Orwhere('id',1007)->get();
  9. echo '<pre>';
  10. print_r($res->toArray());
  11. }
  12. }

路由:web.php

  1. <?php
  2. use Illuminate\Support\Facades\Route;
  3. Route::get('/home/whereor','Home@whereor');


4.join() 多表查询

控制器:home.php

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. use Illuminate\Support\Facades\DB;
  5. Class Home extends Controller{
  6. //join查询
  7. public function join(){
  8. $res = DB::table('staff')->join('user','staff.name','=','user.name')->get();
  9. echo '<pre>';
  10. print_r($res);
  11. }
  12. }

路由:web.php

  1. <?php
  2. use Illuminate\Support\Facades\Route;
  3. Route::get('/home/join','Home@join');


二、中间件

  • 定义中间件:Mycheck.php
  1. <?php
  2. namespace App\Http\Middleware;
  3. use Illuminate\Http\Request;
  4. use Closure;
  5. /*
  6. 中间件
  7. 固定格式
  8. */
  9. class Mycheck{
  10. public function handle(Request $request,Closure $next){
  11. $a = 3;
  12. $b = 5;
  13. if($a+$b === 8){
  14. return response('a+b='.($a+$b),200);
  15. }
  16. return $next($request);
  17. }
  18. }
  • 注册中间件:Kernel.php
  1. <?php
  2. namespace App\Http;
  3. use Illuminate\Foundation\Http\Kernel as HttpKernel;
  4. class Kernel extends HttpKernel
  5. {
  6. protected $routeMiddleware = [
  7. //注册中间件
  8. 'mycheck' => \App\Http\Middleware\Mycheck::class,
  9. ];
  10. }
  • 触发中间件:web.php
  1. <?php
  2. use Illuminate\Support\Facades\Route;
  3. Route::get('/home/join','Home@join')->middleware('mycheck');


声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议