Yii2的框架笔记整理

以下为个人经验总结,转载请注明出处,谢谢

1 .request的获取方式

  $request = Yii::$app->request;

2. get参数的获取方式

  $id = $request->get('id',1);获取get的id,默认1

3 .post参数的获取方式

  $id = $request->post('id',1); 获取post的id,默认1

4. 判断是否为get或者post的请求

  $request->isGet; $request->isPost ; 是为true,否为false

5. 获取用户

  ip $request->userIP;

6. 将后台数据传递到前台

  return $this->renderPartial('index',$data);  return $this->render('index',$data);  $data表示传递到前台的数据

7. compact 合并数组

8. 前台   

<?php  echo YiihelpersHtml::encode($str) ?>将$str的html标签转为实体。<?=  echo YiihelpersHtml::process($str)?>去掉html标签

9. 不自己定义父模板,不适用原模板 

  控制器方法:

  public $layout = 'home';//用属性的方法定义父模板

  public function actionIndex(){

    return $this->render('index');

  }

  在view/layout/写一个home.php,自定义一个父模板

10. 在不用的页面之间互相引用   

  <?=$this->render('about'); ?>

11. 模型类

  namespace appmodels;

  use YiidbActiveRecord;

  class Article extends ActiveRecord{}

  在控制器中加入模型方法

  use appmodelsArticle;

  使用封装好的操控数据库的方法

  $xx = Article::findBySql(sql语句)->all();

12. 查询数据

  查询单条数据:id = 5

  $data = Article::find()->where(['id'=>5])->one();    此处的$data是一个对象

  数组: $data = Article::find()->asArray()->all();    此处的$data是一个数组

  将返回的多条数据分段取出,如得到1000条,分别以10条的形式展示,以减少内存占用的方法:

  foreach(Article::find()->batcjh(10) as $article)){

    $data[] = $article;

  }

  like条件andWhere , in条件, !=

  where 查询: where(['and' , [ 'like' , 'cas' , $key.'%' , false ] , [ 'is_delete' => 0] ])->andWhere([ '>' , 'add' , $time])->andWhere(['in' , 'id' , [232,467,14,19,52])->andwhere([ '!=' , 'parent', 0 ])

  left 查询:

  $model = (new Query())

      ->select( ' A.xx , A.xx , B.xx,  B.xx , C.xx' ) 

      ->from(' ti as A')

      ->leftJoin( ' t2 as B ' , ' ti.id = t2.id ')

      ->leftJoin(' t3 as C ' , ' ti.id = t3.id ')

      ->where($where)

      ->orderby(['

        '`id=1`' => SORTDESC,

        'order_num'=> SORTDESC

      '])

13. 添加数据到数据库

  在控制器的方法中

  $Article = new Article();

  $Article->字段1 = '值';

  $Article->字段2 = '值';

  $data = $Article->insert();或者$data = $Article->save();

  以上两种方法返回的都是true或者false;插入到表article;返回插入的数据的is的方法: $id = $Article->attributes['id'];

14. 修改数据库

  //修改记录

  $article = Article::findOne(11);  //查询id为11的这条数据

  $article->title = 'xxxx';

  $article->num = 10;

  $data = $article->update(); 或者$data = $article->save();

  //修改查看次数(单个字段)

  $data = $Article::updateAllCounters(['num'=>1],['id'=>8]); 修改id为8的这条数据

  $data = $this->updateAll(['name'=>'lisa','sex=>0'] , ['ok'=>1] , '额外条件' ) ;

              ↑字段值                          ↑where     ↑order

 

  更新数据库,字段自增+1,2018-6-30更新

  $result = Yii::$app->db->createCommand()->update('app_xwnew_items',['price' =>new Expression('price+1')], "item_id=".$item_id)->execute();

15. 删除数据

  $article = Article::findOne(16);

  $article = Article::find()->where(['id'=>15])->one();    $result = $article->delete();

  $article = Article::find()->where(['id'=>15])->all();  $result = $article[0]->delete();

  $result = Article::deleteAll('id>:id And num<:num',[':id'=>13,':num'=>100]);

16. 多表关联查询

  文章分类表(分类id)->文章表 ,首先在models中简历一个分类表的模型类

  $category = Category::findOne(1);

  $result = $category->hasMany(Article::className(),['cate_id'=>'id'])->all();    hasOne方法则是一对一

17.  with的使用

  $result = Article::find()->with('category')->asArray()->all();    其实是用了article模型类中的getcategory()方法。

  public function getCategory(){

    $category = $this->hasOne(Category::className(),['id'='cate_id'])->asArray();

    return $category;

  }

18. 输出sql语句的方法

  $retuslt->createCommand()->getRawSql();

19. 模型类中的查询 :

  $this->find()->where(['a'=>1])->andwhere(['>'],'add_time',123456)->one();

20. Yii获取验证码的方法

  控制器中 :

  $val = new commonmoblesValidateCode();

  $val->doimg();

  Yii::$app->session['vakudatacode'] = $val->getCode();

21. Yii2中的表单令牌验证加入防止出现404错误

  在表单中加入<input name="_csrf" type="hidden" id="_csrf" value="<?=Yii::$app->request->csrfToken?>"/>

22. 模型类中只查询某些字段

  $this->find()->select('字段1,字段2')->one();

23. 设置头部信息

  $res = Yii::$app->response;

  $res->statusCode = '404';    //设置访问状态

  $res->headers->add('pragma','no-cache');     //设置头部信息

  $res->headers->set('pragma','max-age=5');    //设置头部信息

  $res->header->remove('pragma');                  //设置头部信息

  跳转

  $res->headers->add('location','http://www.baidu.com');

  $this->redirect('http://www.baidu.com',302);

  文件下载

  $res->headers->add('content-disposition','attachement:filename="a.jpg"');

  $res->sendFile('./b.jpg');

24. session应用组件,session文件在phpstudy/tmp/tmp

  $session = Yii::$app->session;

  if($session->isActive){    //判断session是否开启

    echo 'session is actve';

  }

  $session->set('user', '张三');  //设置session

  $session->get('user');    //获取session  

  $session->remove('user');  //删除session

25. cookie应用组件的使用

  首先在每个控制器的命名空间下加上    use Yiiwebcookie

  $cookie = Yii::$app->response->cookie;

  $cookie_array = array('name'=>'user' , 'value'=>'zhangsan');

  $cookie->add(new Cookie($cookie_data));  //重复设置会覆盖

  $cookie->remove('name');

  $cookie = Yii::$app->request->cookies;

  echo $cookie->getValue('user',20);

  $cookie = Yii::$app->request->cookies;   //只读

  $cookie = Yii::$app->response->cookies;    //可写入

26. 使用common文件夹下的类的方法

  在common下的init.php入口配置文件中引入  如:qqQC.class.php

  在项目的控制器中使用 newQC();

 27. db直接执行sql

  $db = Yii::$app->db;

  $a = $db->createCommand($sql)->query();  //查询

  $b = $db->createCommand($sql)->execute();  //其他

28. Yii2设置缓存,将查询出来的数据保存到front/runtime/cache/xxx

  方法:$cache = Yii::$app->cache;

     $cache->("company_detail_".$_POST[''id] , $arr , 时间秒);

  读取:$cache->get( "company_detail_".$id );  读取出来的是一个完成的$arr

29. Yii2页面引入js文件     

  <?=Html::jsFile('public.plug/xxx/xxx.js')?>

30. 创建事务

  $transaction = Yii::$app->db->beginTransaction();

  提交事务

  $transaction->commit();

  回滚

  $transaction->rollback();

  一般使用方法:

  try{

    if(false){

      throw new Exception('这里填写异常信息,如:sorry,保存失败,请稍后再试!');

    } 

  }catch (Exception $e) {

     $transaction->rollBack();
  }

原文地址:https://www.cnblogs.com/fpcing/p/8989278.html