Blogger Information
Blog 48
fans 3
comment 1
visits 37437
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
利用闭包实现查询——2018年5月24日
JackBlog
Original
620 people have browsed it

实例

<?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);

	}



}

运行实例 »

点击 "运行实例" 按钮查看在线实例


Correction status:Uncorrected

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post