1. 模型
    1. orderby的使用:
      ->orderBy(['addtime'=>SORT_DESC, 'sort'=>SORT_ASC])->all()
    2. 在使用find()查询的时候, 指定查询字段:
      find()->select('id, title, content') 指定查询的字段
    3. 块赋值, 使用attributes, 比如 $psychological->attributes = $input; 把数组一次性赋值给attributes 属性, 但是要注意, 要确保模型类中的rules方法, 已经包含了要赋值的字段. 否则attributes 属性接收不到值. 就不能保存成功
    4. where 作为查询条件单独拿出来的时候, 想使用  <  >  >=  <=  <>  进行范围查询的时候, 要怎么写?
      $where = [
      'and',
      ['<', 'minscore', $score],
      ['>', 'maxscore', $score],
      ];
      //查询满足minscore<$score并且maxscore>$score 的记录
      -
      //随机查询数据库中的数据
      $ids = [];
      for($i=1; $i<=15; $i++){
      $ids[] = mt_rand(1,3993); //生成随机数组
      }
      $where = [
      'and',
      ['in', 'id', $ids], //查询id 在 $ids 数组里的数据
      ];
    5. yii2中同时连接两个或以上数据库:(如果在本地开发完,传到线上服务器, 需要把配置的数据库的用户名和密码改成线上数据库的
      )
      1. 在config目录下web.php文件中的components数组里配置

        'db2' => [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=localhost;dbname=quickapp',
        'username' => 'root',
        'password' => 'root',
        'charset' => 'utf8',
        ],
      2. 在继承ActiveRecord的模型中设置表名,rules等,必须要注意一点, yii默认连接的是components里面的db设置的数据库, 所以当连接其他数据库的时候, 就必须要重写 getDb() 方法, 很简单

        public static function getDb()
        {
        return \Yii::$app->db2; //db2就是components里的db2下标
        }

        OK, 可以使用了.

    6.  yii打印SQL语句:
      echo RecycleModel::find()
      ->alias('r')
      ->select('r.name as rubbish, c.id, c.name, c.code, c.inc, c.des,c.req')
      ->leftJoin(['c'=>RecycleCateModel::tableName()], 'r.category_id=c.id')
      ->where($where)
      ->orderBy(['modified'=>SORT_DESC])
      ->limit('10')
      ->asArray()->createCommand()->getRawSql();exit;
    7. 添加数据()

      $usercode = \Yii::$app->db->createCommand()
      ->batchInsert(UserVoucher::tableName(), ['code', 'cat_id','userId', 'gettime', 'expire'], [
      [$code['code'], $id, $userId, time(), $code['expire']],
      ])->execute(); // \Yii::$app->db 这里的db, 如果换成db2, 就是往db2数据库里插入数据.
    8. 连表查询分页
      $count = VoucherCode::find()
      ->alias('v')
      ->leftJoin(['c'=>RubbishCate::tableName()], 'v.cat_id=c.id and v.is_delete=0')
      ->where($where)
      ->count(); //查询符合连表数据总数
      $p = new Pagination(['totalCount'=>$count, 'pageSize'=>15]);
      $code = VoucherCode::find()
      ->alias('v')
      ->leftJoin(['c'=>RubbishCate::tableName()], 'v.cat_id=c.id and v.is_delete=0')
      ->select('v.*, c.name')
      ->where($where)
      ->offset($p->offset)
      ->limit($p->limit)
      ->asArray()
      ->all(); //查询数据
      return $this->render('/rubbish-voucher/list', ['code'=>$code, 'pagination'=>$p]);
      //views视图调用
      <?php echo \yii\widgets\LinkPager::widget([
      'pagination' => $pagination,
      'prevPageLabel' => '上一页',
      'nextPageLabel' => '下一页',
      'firstPageLabel' => '首页',
      'lastPageLabel' => '尾页',
      'maxButtonCount' => 5,
      'options' => [
      'class' => 'pagination',
      ],
      'prevPageCssClass' => 'page-item',
      'pageCssClass' => "page-item",
      'nextPageCssClass' => 'page-item',
      'firstPageCssClass' => 'page-item',
      'lastPageCssClass' => 'page-item',
      'linkOptions' => [
      'class' => 'page-link',
      ],
      'disabledListItemSubTagOptions' => ['tag' => 'a', 'class' => 'page-link'],
      ])
      ?>
    9. 条件查询:
      $status = \Yii::$app->request->get('status', '');   //获取用户传入的条件
      $where = [];
      if($status != ''){
      $where['status'] = $status;
      }
      $where['is_delete'] = 0;
    10. 多对多关联
      //课程表和用户表多对多关联, 课程course模型里获取用户表字段, 中间表为 user_course, 中间表写在viaTable()里
      public function getUser()
      {
      return $this->hasMany(User::className(), ['id'=>'uid'])->viaTable('user_course', ['course_id'=>'id']);
      }
      //或者使用via()
      //获取关联表的属性
      $user = Course::findOne($v['id'])->user;
      //统计有多少人
      $num = count(Course::findOne($v['id'])->user);
    11. 接口返回分页数据
      $count = Course::find()->where($where)->count();  //数据总数
      $p = new Pagination(['totalCount'=>$count, 'pageSize'=>$pagesize]); //实例化分页类
      $course = Course::find()->select('id, title, pic_url, sections, teacher, fee, free')->where($where)->offset(($page-1)*$pagesize)->limit($p->limit)->all(); //前端传入第几页$page和每页显示多少条$pagesize, 主要是offset方法里的参数怎么写

      或者这么写

      $course = Course::find()->select('id, title, pic_url, sections, teacher, fee, free')->where($where)->offset(($page-1)*$pagesize)->limit($pagesize)->all();
    12. $model->errors; 打印数据验证过程中的错误信息 
    13. 根据where条件查询指定字段, 拼接field时候, 如果有重复字段仍然可以正常查询的. 并且如果没有指定where条件, 默认查询几个字段
      if(isset($refund_rate))
      $where['refund_rate'] = $refund_rate;
      if(isset($row_sate_rate))
      $where['row_sate_rate'] = $row_sate_rate;
      if(isset($film_playnum))
      $where['film_playnum'] = $film_playnum;
      if(isset($layout_ratio))
      $where['layout_ratio'] = $layout_ratio;
      if(isset($person_time))
      $where['person_time'] = $person_time;
      if(isset($date))
      $where['date'] = $date;
      //设置查询的指定字段
      $field = '';
      if(isset($where)){
      $field = implode(',', array_keys($where));
      }
      $field .= ', id, movie_name, split_box_total, synthesize_total, date '; //多加date 并不会报错
      $result = TicketMovie::find()->select($field)->where($where)->offset(($page-1)*$pagesize)->limit($pagesize)->asArray()->all();

yii框架学习(二)的更多相关文章

  1. Yii框架学习笔记(二)将html前端模板整合到框架中

    选择Yii 2.0版本框架的7个理由 http://blog.chedushi.com/archives/8988 刚接触Yii谈一下对Yii框架的看法和感受 http://bbs.csdn.net/ ...

  2. Yii框架学习 新手教程(一)

    本人小菜鸟一仅仅,为了自我学习和交流PHP(jquery,linux,lamp,shell,javascript,server)等一系列的知识,小菜鸟创建了一个群.希望光临本博客的人能够进来交流.寻求 ...

  3. Struts2框架学习(二) Action

    Struts2框架学习(二) Action Struts2框架中的Action类是一个单独的javabean对象.不像Struts1中还要去继承HttpServlet,耦合度减小了. 1,流程 拦截器 ...

  4. YII框架学习(二)

    YII框架的增删改查 例:一个新闻表的增删改查: (1)首先使用gii工具生成控制器和模型 (2)控制器 <?php class NewsController extends Controlle ...

  5. Yii 框架学习--01 框架入门

    Yii 是一个高性能的,适用于开发 WEB2.0 应用的 PHP 框架. Yii目前有两个主要的版本: 2.0 和 1.1.本文以YII 2.0.7为例. 环境需求 Yii2.0 框架有一些系统上的需 ...

  6. PHP开发框架之YII框架学习——碾压ThinkPHP不是梦

      前  言 JRedu 程序猿是一种慵懒的生物!能少敲一行代码,绝对不会多敲一个字符!所以,越来越多的开发框架应运而生,在帮助我们完成功能的同时,极大程度上也帮我们节省了人力物力,而且也提高了系统的 ...

  7. Yii框架学习资源盘点

    盘点一些Yii框架的常用学习资源. 1.Yii中文论坛 https://www.yiichina.com/ 2.Yii中文网 http://www.yii-china.com/ 3.魏曦教你学Yii2 ...

  8. <yii 框架学习> yii 框架改为中文提示

    工作需要用到yii框架,但发现yii框架自带的提示都是英文的.上网找资料才发现其实可以自己陪置 . 将项目protected/config/main.php里的app配置加上language=> ...

  9. YII框架学习(一)

    1.安装: windows:将php命令所在的文件夹路径加入到环境变量中,通过cmd命令:进入yii框架中的framework目录,执行: php yiic webapp ../cms linux:类 ...

随机推荐

  1. Spring 如何解决循环依赖问题?

    在关于Spring的面试中,我们经常会被问到一个问题,就是Spring是如何解决循环依赖的问题的. 这个问题算是关于Spring的一个高频面试题,因为如果不刻意研读,相信即使读过源码,面试者也不一定能 ...

  2. Typora的使用-规整笔记 让我以后的笔记内容更加整齐

    以后我用typora写笔记使用这种排版方式, 且可以方便的看到大纲. 大标题二级标题 内容分类 三级标题 内容讲解 四级标题 内容分块 五级标题

  3. Minimum Cut(2015沈阳online)【贪心】

    Minimum Cut[贪心]2015沈阳online 题意:割最少的边使得图不连通,并且割掉的边中有且仅有一条是生成树的边. 首先,我们选择一条树中的边进行切割,此时仅考虑树上的边集,有两种情况:1 ...

  4. Photon Server初识(二) ---通过NHibernate 映射数据库

    一.下载 NHibernate.dill 官网:https://nhibernate.info 或者通过NuGet下载(详情看上一节) 二.新建一个项目,并引入包 引入包 三.配置(重点) 1.配置x ...

  5. centerOS7安装lnmp环境

    视频地址: https://www.bilibili.com/video/av55251610?p=65 安装nginx http://nginx.org 点击 download vim /etc/y ...

  6. 查看linux服务器信息

    1.  vmstat 查看服务器内存,CPU等信息 一般是通过两个数字参数来完成的,第一个参数是采样时间间隔,单位是秒, 第二个参数是采样的次数 r:    表示运行队列,如果队列过大说明CPU很繁忙 ...

  7. asp.net 8 Request,Response,Server

    Request成员: 1.Request.UrlReferrer 获取请求的来源,可以防盗链 Response.Write(Request.Url.ToString());//获取当前请求的URL地址 ...

  8. mysql if else count 计数

    select mobile,avg(total),sum(click_day*click_money),sum(click_day),count(push_status),sum(clicks),co ...

  9. luogu题解P2486[SDOI2011]染色--树链剖分+trick

    题目链接 https://www.luogu.org/problemnew/show/P2486 分析 看上去又是一道强行把序列上问题搬运到树上的裸题,然而分析之后发现并不然... 首先我们考虑如何在 ...

  10. loj 2759「JOI 2014 Final」飞天鼠

    loj 这题有在一棵树上上升或者下降的操作,稍加分析后可以发现上升操作如果不是一定要做(指高度不足以到下一棵树或者是最后到达\(n\))就不做,下降操作也是如果不是一定要做(指到达下一棵树时高度过高) ...