zoukankan      html  css  js  c++  java
  • 【TP5学习笔记三】

    1.查询范围

    对于一些常用的查询条件,我们可以封装成查询范围来进行方便的调用。
    例如,邮箱地址为 thinkphp@qq.com 和status为1这两个常用查询条件,可以定义为模型类的两个查询范围
    方法:

    <?php
    namespace appindexmodel;
    use thinkModel;
    class User extends Model
    {
        // 定义类型转换
        protected $type = [
            'birthday' => 'timestamp:Y/m/d',
        ];
        // 定义自动完成的属性
        protected $insert = ['status'];
        // status修改器
        protected function setStatusAttr($value, $data)
        {
            return '流年' == $data['nickname'] ? 1 : 2;
        }
        // status读取器
        protected function getStatusAttr($value)
        {
            $status = [-1 => '删除', 0 => '禁用', 1 => '正常', 2 => '待审核'];
            return $status[$value];
        }
        // email查询
        protected function scopeEmail($query)
        {
            $query->where('email', 'thinkphp@qq.com');
        }
        // status查询
        protected function scopeStatus($query)
        {
            $query->where('status', 1);
        }
    }        
    

     查询范围方法的定义规范为:

      scope + 查询范围名称

    支持多次调用 scope 方法,并且可以追加新的查询及链式操作,例如:

    // 根据查询范围获取用户数据列表
    public function index()
    {
    //
    $list = UserModel::scope('email')
    ->scope('status')
    ->scope(function ($query) {
    $query->order('id', 'desc');
    })
    ->all();
    foreach ($list as $user) {
    echo $user->nickname . '<br/>';
    echo $user->email . '<br/>';
    echo $user->birthday . '<br/>';
    echo $user->status . '<br/>';
    echo '-------------------------------------<br/>';
    }
    }
    

      

  • 相关阅读:
    Shell for
    rsync 目录 斜杠
    shell local
    linux secureCRT utf-8编码显示
    eclipse maven 项目不显示 target目录
    如何打印身份证实际大小
    linux 去掉 ^M
    hibernate 之 集合映射中list映射
    hibernate 之 复合主键映射
    hibernate 之 组件映射
  • 原文地址:https://www.cnblogs.com/VanQ/p/7008968.html
Copyright © 2011-2022 走看看