tp笔记


20.模型查询范围和输出

<pre><code class="language-php"> 一.模型查询范围 1.在模型端创建一个封装的查询或写入方法,方便控制器端等调用; 2.比如,封装一个筛选所有性别为男的查询,并且只显示部分字段 5 条; 3.方法名规范:前缀 scope,后缀随意,调用时直接把后缀作为参数使用; publicfunctionscopeGenderMale($query) { $query-&gt;where('gender','男')-&gt;field('id,username,gender,email') -&gt;limit(5); } 4.在控制器端,我们我们直接调用并输出结果即可; publicfunctionqueryScope() { $result=UserModel::scope('gendermale')-&gt;select(); //$result=UserModel::gendermale()-&gt;select(); returnjson($result); } 5.也可以实现多个查询封装方法连缀调用,比如找出邮箱 xiao 并大于 80 分的; publicfunctionscopeEmailLike($query,$value) { $query-&gt;where('email','like','%'.$value.'%'); } publicfunctionscopePriceGreater($query,$value) { $query-&gt;where('price','&gt;',80); } $result=UserModel::emailLike('xiao')-&gt;priceGreater(80) -&gt;select(); 6.查询范围只能使用 find()和 select()两种方法; 7.全局范围查询,就是在此模型下不管怎么查询都会加上全局条件; //全局范围查询 protectedfunctionbase($query) { $query-&gt;where('status',1); } 8.在定义了全局查询后,如果某些不需要全局查询可以使用 useGlobalScope 取消; UserModel::useGlobalScope(false) 9.当然,设置为 true,则开启全局范围查询,注意:这个方法需要跟在::后面; UserModel::useGlobalScope(true) 二.模型输出方式 1.通过模版进行数据输出; public function view() { $user = UserModel::get(21); $this-&gt;assign('user', $user); return $this-&gt;fetch(); } 2.根据错误提示,可以创建相对应的模版,然后进行数据显示; {$user.username}. {$user.gender}. {$user.email} 3.使用 toArray()方法,将对象按照数组的方式输出; $user=UserModel::get(21); print_r($user-&gt;toArray()); 4.和之前的数据集一样,它也支持 hidden、append、visible 等方法; print_r($user-&gt;hidden(['password,update_time'])-&gt;toArray()); 5.toArray()方法也支持 all()和 select()等列表数据; print_r(UserModel::select()-&gt;toArray()); 6.使用 toJson()方法将数据对象进行序列化操作,也支持 hidden 等方法; print_r($user-&gt;toJson());</code></pre>

页面列表

ITEM_HTML