宠尺合假纱横镣锈拖细稻莲擂
数据表结构:
使用表达式查询:
D:\phpStudy\PHPTutorial\WWW\tp5\application\index\controller\Index.php:
<?php namespace app\index\controller; use think\Db; class Index { public function index() { dump( Db::table('staff') ->field(['name','salary']) ->where('id','=',6) ->find() ); } }
执行:
查询id>6的第一条员工信息
<?php namespace app\index\controller; use think\Db; class Index { public function index() { dump( Db::table('staff') ->field(['name','salary']) ->where('id','>',6) ->find() ); } }
执行:
查询工资大于3000的员工信息
<?php namespace app\index\controller; use think\Db; class Index { public function index() { dump( Db::table('staff') ->field(['name','salary']) ->where('salary','>',3000) ->select() ); } }
执行:
2.使用数组查询多个条件
<?php namespace app\index\controller; use think\Db; class Index { public function index() { dump( Db::table('staff') ->field(['name','salary']) ->where([ 'id'=>['>',4], 'salary'=>['>',3000] ]) ->select() ); } }
执行:
3.闭包查询
<?php namespace app\index\controller; use think\Db; class Index { public function index() { dump( Db::table('staff') ->field(['name','salary']) ->where(function($query){//参数固定,必须是query $query->where('id>4') ->where('salary','>',3000); }) ->select() ); } }
执行:
这两个查询条件还可以使用数组进行组合
<?php namespace app\index\controller; use think\Db; class Index { public function index() { dump( Db::table('staff') ->field(['name','salary']) ->where(function($query){//参数固定,必须是query $query->where([ 'id'=>['>',4], 'salary'=>['>',3000] ]); }) ->select() ); } }
执行:
闭包查询的好处是,当条件比较复杂时使用很方便,获取用于接收外部变量
闭包使用外部变量
<?php namespace app\index\controller; use think\Db; class Index { public function index() { $id=4; $salary=3000; dump( Db::table('staff') ->field(['name','salary']) ->where(function($query) use($id,$salary){//参数固定,必须是query $query->where([ 'id'=>['>',$id], 'salary'=>['>',$salary] ]); }) ->select() ); } }
执行:
将fiel(),where()全部打包到闭包中
<?php namespace app\index\controller; use think\Db; class Index { public function index() { dump( Db::select(function($query){ $query->table('staff') ->field(['name'=>'姓名','salary'=>'工资']) ->where([ 'id'=>['>',4], 'salary'=>['>',4000] ]); }) ); } }
执行:
闭包使用外部变量
<?php namespace app\index\controller; use think\Db; class Index { public function index() { $id=4; $salary=4000; dump( Db::select(function($query) use($id,$salary){ $query->table('staff') ->field(['name'=>'姓名','salary'=>'工资']) ->where([ 'id'=>['>',$id], 'salary'=>['>',$salary] ]); }) ); } }
执行:
或查询
查询id>4或者id<2的员工信息
<?php namespace app\index\controller; use think\Db; class Index { public function index() { dump(Db::table('staff') ->field(['name']) ->whereOr('id>4') ->whereOr('id<2') ->select()); } }
执行:
狄顶绵觅次够接掇拔獭仑谋紊