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

       

    14. $location = Location::find()
                  ->where(['user_id' => $user_id])
                  ->andWhere(['and', ['>', 'location_update_time', $time], ['<', 'location_update_time', $time+86400]])
                  ->andWhere(['<>', 'location_name', ''])
                  ->groupBy('location_name')
                  ->having("count('location_name')>30")        //字符串条件表达式就是原生SQL语句的条件写法
                  ->orderBy('location_update_time desc')
                  ->limit(50)
                  ->asArray()
                  ->all();

       

    15. yii  updateAll  的使用方法:https://www.yiichina.com/tutorial/1842