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 \Yii\helpers\Html::encode($str) ?>将$str的html标签转为实体。<?=  echo \Yii\helpers\Html::process($str)?>去掉html标签

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

  控制器方法:

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

  public function actionIndex(){

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

  }

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

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

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

11. 模型类

  namespace app\models;

  use \Yii\db\ActiveRecord;

  class Article extends ActiveRecord{}

  在控制器中加入模型方法

  use app\models\Article;

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

  $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)

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 \common\mobles\ValidateCode();

  $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 Yii\web\cookie

  $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入口配置文件中引入  如:qq\QC.class.php

  在项目的控制器中使用 new\QC();

 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

Yii 2.0 权威指南 本教程的发布遵循 Yii 文档使用许可. 版权所有 2014 (c) Yii Software LLC. 介绍 已定稿 关于 Yii 已定稿 从 Yii 1.1 升级 入门 已定稿 安装 Yii 已定稿 运行应用 已定稿 第一次问候 已定稿 使用 Forms 已定稿 玩转 Databases 已定稿 用 Gii 生成代码 已定稿 更上一层楼 应用结构 已定稿 结构概述 已定稿 入口脚本 已定稿 应用 已定稿 应用组件 已定稿 控制器(Controller) 已定稿 视图(View) 已定稿 模型(Model) 已定稿 过滤器 已定稿 小部件(Widget) 已定稿 模块(Module) 已定稿 前端资源(Asset) 已定稿 扩展(extensions) 请求处理 已定稿 运行概述 已定稿 引导(Bootstrapping) 已定稿 路由(Route)引导与创建 URL 已定稿 请求(Request) 已定稿 响应(Response) 已定稿 Sessions(会话)和 Cookies 已定稿 错误处理 已定稿 日志 关键概念 已定稿 组件(Component) 已定稿 属性(Property) 已定稿 事件(Event) 已定稿 行为(Behavior) 已定稿 配置(Configurations) 已定稿 类自动加载(Autoloading) 已定稿 别名(Alias) 已定稿 服务定位器(Service Locator) 已定稿 依赖注入容器(DI Container) 配合数据库工作 编撰中 数据访问对象(DAO) - 数据库连接、基本查询、事务和模式操作 编撰中 查询生成器(Query Builder) - 使用简单抽象层查询数据库 编撰中 活动记录(Active Record) - 活动记录对象关系映射(ORM),检索和操作记录、定义关联关系 编撰中 数据库迁移(Migration) - 在团体开发中对你的数据库使用版本控制 待定中 Sphinx 待定中 Redis 待定中 MongoDB 待定中 ElasticSearch 接收用户数据 编撰中 创建表单 已定稿 输入验证 编撰中 文件上传 待定中 多模型同时输入 显示数据 编撰中 格式化输出数据 待定中 分页(Pagination) 待定中 排序(Sorting) 编撰中 数据提供器 编撰中 数据小部件 编撰中 主题 安全 编撰中 认证(Authentication) 编撰中 授权(Authorization) 编撰中 处理密码 待定中 客户端认证 待定中 安全领域的最佳实践 缓存 已定稿 概述 已定稿 数据缓存 已定稿 片段缓存 已定稿 分页缓存 已定稿 HTTP 缓存 RESTful Web 服务 已定稿 快速入门 已定稿 资源 已定稿 路由 已定稿 格式化响应 已定稿 授权验证 已定稿 速率限制 已定稿 版本化 已定稿 错误处理 已定稿 测试
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值