• Yii2 学习心得


    <?php
    /**
    * Yii框架的数据库查询是基于pdo来执行的
    * main-local 这种凡是带local的是为了避免开发冲突设计的,可以在本地修改配置,但是不要提交就可以
    */

    //sql查询
    Yii::$app->db->createCommand('select * from post')->queryAll();
    Yii::$app->db->createCommand('select * from post')->queryOne();

    //根据id查询sql
    Yii::$app->db->createCommand('select * from post where id = :id and status = :status')
    ->bindValue(':id',$_GET['id'])
    ->bindValue(':status',1)
    ->queryAll();


    //使用ActiveRecord查询
    Post::find()->where(['id'=>1])->all();
    Post::find()->where(['id'=>1])->one();

    //设置查询条件
    $posts = Post::find()->where(['AND',['status'=>2],['author_id'=>1],['like','title','标题内容']])->orderby('id')->all();

    findBySql();//这也是一种查询方法

    //或者

    Post::findOne(1);
    Post::findAll(['id'=>1,]);

    //输出id
    $model = Post::findOne(1);
    echo $model->id;


    //curl其中save可以代替insert和update
    //添加
    $post = new Post();
    $post->id = 1;
    $post->status = 2;
    $post->save();//等同于insert

    //修改
    $post = Post::findOne($id);
    $post->status = 1;
    $post->save();//等同于修改

    //删除
    $post = Post::findOne($id);
    $post->delete();


    //DetailView用于显示一条记录的数据
    <?= DetailView::widget([
    'model' => $model,
    'attributes' => [
    'id',
    'title',
    'content:ntext',
    'tags:ntext',
    'status',
    'create_time:datetime',
    'update_time:datetime',
    'author_id',
    ],
    ]),

    //。。。。。。。还可以添加属性控制表单样式 
    'template'=>'<tr><th style=" 120px;">{label}</th><td>{value}</td></tr>',//设置label的样式
    'options'=>['class'=>'table table-striped table-bodered detail-view'],//设置整个表格的属性样式
    ?>


    像上面的这种ntext、datetime这种的都是展示的格式
    ntext会把网页的标签都展示出来
    datetime展示的yii的时间形式Sep 23, 2015 4:51:54 PM

    变化时间那么就用这种样子的
    [
    'attribute'=>'update_time',
    'value'=>date('Y-m-d H:i:s',$model->update_time),
    ],


    //ListView和GirdView可以对数据进行分页、排序和过滤
    hasOne用于多对一、一对一的情况
    hasMany用于一对多的情况


    例如:我的model层代码有
    public function getStatus0()
    {
    return $this->hasOne(Poststatus::className(), ['id' => 'status']);
    }

    那么我在展示的时候就可以写成:
    [
    'label'=>'状态',
    'value'=>$model->status0->name,
    ],

    或者

    public function getAuthor()
    {
    return $this->hasOne(Adminuser::className(), ['id' => 'author_id']);
    }

    展示也可以写成
    [
    'attribute'=>'author_id',
    'value'=>$model->author->nickname,
    ]

    //别名-用来替代网址或者一些路径之类的(必须用@开头)
    Yii::setAlias('@foo','/path/to/foo');//文件路径别名
    Yii::setAlias('@foo','http://www.baidu.com');//URL别名

    别名的使用

    $cache = new FileCache([
    'cachePath'=>'@runtime/cache',
    ]);

    //下拉框示例
    <?= $form->field($model, 'status')
    ->dropDownList(['1'=>'草稿','2'=>'已发布'],['prompt'=>'请选择状态']);
    ?>

    那么和数据库交互以后的下拉框可以这样写
    <?php
    $poststatus = Poststatus::find()->all();//model也是要注意引用
    $allStatus = ArrayHelper::map($poststatus,'id','name');//类文件需要引用以后才可以这样简写ArrayHelper
    ?>
    <?= $form->field($model, 'status')
    ->dropDownList($allStatus,
    ['prompt'=>'请选择状态']);?>

    又或者这样写:
    <?php
    $psArray = Yii::$app->db->createCommand('select id,name from poststatus')->queryAll();
    $allStatus = ArrayHelper::map($psArray,'id','name');
    ?>


    又或者用query-buider
    <?php
    $allStatus = (new yiidbquery())
    ->select(['name','id'])
    ->from('poststatus')
    ->indexBy('id')
    ->column();
    ?>


    或者
    <?php
    $allStatus = Poststatus::find()
    ->select(['name','id'])
    ->orderBy('position')
    ->indexBy('id')
    ->column();
    ?>


    //from查询(支持将查询出来的结果当成一张表再查询)
    $subQuery = (new yiidbQuery())->select('id')->from('user')->where('status=1');
    $query->from(['u'=>$subQuery]);


    //limit的用法
    $query->limit(10)->offset(20); 表示从第20条开始取数,取10条记录


    关于查询的一些语法可以参考http://www.yiichina.com/doc/guide/2.0/db-query-builder

    图片总结:

     

     preg_split('/s*,s*/',trim($tags),-1,PREG_SPLIT_NO_EMPTY);匹配空白字符开头或者空白字符结尾的字符串并且转换成数组

    array_values  取得数组中所有的值(而不是键名)
    array_diff   取得的是数组的差集(也就是两个数组相比较,其中一个数组比另一个数组多出的部分)

    array_diff($new,$old)  和  array_diff($old,$new)是有差别的


    上面我们说过了设置时间在id查询单个model的时候的例子
    接下来我们在说一下在 GridView::widget中时间的设置
    [
        'attribute'=>'update_time',
        'format'=>['date','php:Y-m-d H:i:s'],
    ],






    声明一下GridView::widget的例子:
    <?= GridView::widget([
            'dataProvider' => $dataProvider,
            'filterModel' => $searchModel,
            'columns' => [
                //这一行就代表的是序列号
               // ['class' => 'yiigridSerialColumn'],

    //            'id',
                ['attribute'=>'id',
                 'contentOptions'=>['width'=>'30px;'],//设置单元格宽度
                ],
                'title',
                //'author_id',
                ['attribute'=>'author_id',
                 'value'=>'author.nickname',
                ],
    //            'content:ntext',
                'tags:ntext',
    //            'status',
                ['attribute'=>'status',
                 'value'=>'status0.name',
                    //一下这个属性是用来设置下拉查询的样式以及数据交互的查询的
                  'filter'=>commonmodelsPoststatus::find()
                    ->select(['name','id'])//查询这两个字段
                    ->orderBy('position')//根据数据库这个字段实现排序
                    ->indexBy('id')//用数据库查到的作为索引
                    ->column(),//查询列数据
                ],
                // 'create_time:datetime',
    //             'update_time:datetime',
                [
                    'attribute'=>'update_time',
                    'format'=>['date','php:Y-m-d H:i:s'],
                ],


                ['class' => 'yiigridActionColumn'],//这一行代表的是查看、修改、删除
            ],
        ]); ?>




    //文章内容太长做截取
    [
        'attribute'=>'content',
        'value'=>function($model){
            $tmpStr = strip_tags($model->content);//去掉html的标签
            $tmplength = mb_strlen($tmpStr);//计算长度
            return mb_substr($tmpStr,0,20,'utf-8').(($tmplength>20)?'...':'');//判断长度大于20以后做拼接
        }
    ],

    这样截取直接在代码中写有时候可能太过于繁琐不好维护,那么我们就可以封装类

    在model层做一个封装

    public function getBeginning(){
    $tmpStr = strip_tags($this->content);
    $tmpLen = mb_strlen($tmpStr);
    return mb_substr($tmpStr,0,20,'utf-8').(($tmpLen)>20?'...':'');
    }

    接下来就可以在试图层调用了

     [
    'attribute'=>'content',
    'value'=>'beginning',
    // 'value'=>function($model){
    // $tmpStr = strip_tags($model->content);//去掉html的标签
    // $tmplength = mb_strlen($tmpStr);//计算长度
    // return mb_substr($tmpStr,0,20,'utf-8').(($tmplength>20)?'...':'');//判断长度大于20以后做拼接
    // }
    ],

    图文:

    
    

     

    上述错误是字段重复导致的,检查数据表,更换字段,同时更换规则即可!

    或者在查询的时候指定表名就不用这么大改了:

  • 相关阅读:
    Python的Flask框架开发RESTful API
    自研接口测试平台(Django2+Bootstrap3+Unittest)
    接口自动化测试平台 http://120.79.232.23
    ​性能优化指南:性能优化的一般性原则与方法
    性能优化指南:性能优化的一般性原则与方法
    ​性能优化指南:性能优化的一般性原则与方法
    开源自动化测试平台介绍一览
    开源自动化测试平台介绍一览
    App自动化测试方案
    SQL Server中取两个表的交集,并集和差集
  • 原文地址:https://www.cnblogs.com/findher/p/10610573.html
Copyright © 2020-2023  润新知