实例
<?php namespace app\index\controller; use think\Controller; use app\index\model\User as UserModel;//设置模型类的别名,防止冲突 class User extends Controller { public function query() { // 1、单条记录:get(主键\闭包) // 闭包:就是一个匿名回调函数,将函数作为参数传递 // 用闭包来创建查询条件 $user = UserModel::get(function($query){ $query->where('jb','>',1000); }); dump($user); echo '<hr>'; //============================================ //2、多条记录查询 //返回值是二维数组/对象数组 $users = UserModel::all(); $users = UserModel::all(function($query){ $query->where('jb','<',100000); }); foreach ($users as $user) { echo '用户名:'.$user->username.'<br>'; echo '密码:'.$user->password.'<br>'; } echo '<hr color="red">'; 采用闭包来实现将请求变量注入到闭包条件中 $username = $this->request->param('username') ?: '123456'; $users = UserModel::all(function($query) use ($username) { $query->where('username','=',$username); }); dump($users); } }
运行实例 »
点击 "运行实例" 按钮查看在线实例