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. Mysql-Sqlalchemy-ORM-多外键关联

    创建表结构:orm_many_fk.py from sqlalchemy import Integer, ForeignKey, String, Column,create_engine from s ...

  2. 怎样理解NodeList的动态集合与静态集合

    NodeList 有两种, 一种是动态集合, 一种是静态集合, 所谓动态集合, 主要是 Node.prototype.childNodes; 返回的子节点集合对文档的节点增删改会即时改变; 而静态集合 ...

  3. 如何为 esp32 编译和配置及烧写 MicroPython 固件。

    MicroPython 在 esp-idf (esp32) 上编译固件 esp32 编译 micropython 的固件相关的资料应该很多吧,我也会出一篇,但会额外讲一些 linux 的东西的. 资料 ...

  4. 利用Cmake 将最新版本OBS编译成windows版本。

    准备工作: 1. VS2013 的最新更新版或者VS2015 2. QT Creater 5.7   https://www.qt.io/ 3.  CMake (cmake-gui) 4. obs 依 ...

  5. docker之常见错误

    1. docker run -d --name showdoc -p 4999:80 -v /showdoc_data/html:/var/www/html/ star7th/showdoc WARN ...

  6. java enum类自定义属性

    enum类自定义属性 这就是enum比static静态变量好用的地方了,可以赋予每一个枚举值若干个属性,例如 实例1: public enum GasStationChannel { ZH(" ...

  7. flutter: Another exception was thrown: Navigator operation requested with a context that does not include a Navigator.

    import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends State ...

  8. Phoenix设置联合主键

    1例如 create table test12(email varchar not null,id integer not null,name varchar not null,age integer ...

  9. C获取数组长度

    c语言中,定义数组后可以用sizeof命令获得数组的长度(可容纳元素个数) 如: { int data[4]; int length; length=sizeof(data)/sizeof(data[ ...

  10. 单节点FastDFS与Nginx部署

    一.安装基本组件 1.安装编译需要的组件,必安装组件. yum install gcc-c++ 2.安装libevent函数库.pcre-devel zlib-devel必安装组件.     yum ...