本文作者:心月

YII2高级版框架搭建完整博客系统教程——文章浏览次数统计

心月IT博客 03-17
YII2高级版框架搭建完整博客系统教程——文章浏览次数统计摘要:通过扩展表记录文章浏览次数统计,然后实现文章统计功能。

1、创建数据表

CREATE TABLE `post_extends` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '自增ID',
  `post_id` int(11) DEFAULT NULL COMMENT '文章id',
  `browser` int(11) DEFAULT '0' COMMENT '浏览量',
  `collect` int(11) DEFAULT '0' COMMENT '收藏量',
  `praise` int(11) DEFAULT '0' COMMENT '点赞',
  `comment` int(11) DEFAULT '0' COMMENT '评论',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=38 DEFAULT CHARSET=utf8 COMMENT='文章扩展表';

2、gii生成PostExtendsModel

生成PostExtendsModel后记得修改继承类为BaseModel

gii生成PostExtendsModel

3、在PostsController的文章详情方法中添加浏览统计功能

/**
 * 文章详情
 * @param $id
 * @return \yii\web\Response
 */
public function actionView($id)
{
    $model = new PostsForm();
    $data = $model->getViewById($id);

    //文章浏览统计
    $modelExtend = new PostExtendsModel();
    $modelExtend->upCounter(['post_id'=>$id],'browser',1);

    return $this->render('view',['data'=>$data]);

}

文章浏览统计功能

4、在扩展model中实现文章统计方法

/**
 * @param $cond     统计条件
 * @param $attibute 统计字段
 * @param $num      每次数据变化值
 */
public function upCounter($cond, $attibute,$num)
{
    //查询文章扩展模型数据是否存在,不存在则创建,存在则更新统计数据
    $counter = $this->findOne($cond);
    if (!$counter){
        $this->setAttributes($cond);
        $this->$attibute = $num;
        $this->save();
    }else{
        $countData[$attibute] = $num;
        //更新$attibute的值,比如初始值为10,$num为1,执行此方法后$attibute的数据表记录值变为11
        $counter->updateCounters($countData);
    }
}

文章浏览统计方法的实现

5、把统计数据查询返回给文章详情,然后在详情页显示

修改PostsForm方法

/**
 * 获取文章详情
 * @param $id
 * @throws NotFoundHttpException
 */
public function getViewById($id)
{
    $res = PostsModel::find()->with('relate.tag','extend')->where(['id'=>$id])->asArray()->one();
    if (!$res)
        throw new NotFoundHttpException('文章不存');

    $res['tags']=[];
    if(isset($res['relate']) && !empty($res['relate'])){
        foreach ($res['relate'] as $list){
            $res['tags'][]=$list['tag']['tag_name'];
        }
    }
    unset($res['relate']);

    return $res;
}

文章详情数据获取添加扩展关联

postsModel中实现扩展关联方法获取文章浏览数据

public function getExtend()
{
    return$this->hasOne(PostExtendsModel::className(),['post_id'=>'id']);
}

文章扩展关联方法实现

文章详情展示页面中输出浏览统计数据

文章浏览统计数据展示

统计数据页面展示效果

统计数据页面展示效果


文章版权及转载声明:

本文由 心月IT技术博客 博主整理于 03-17
若转载请注明原文及出处:https://www.xinyueseo.com/yii/191.html

分享到:
赞(
发表评论
快捷输入:

验证码

    评论列表 (有 0 条评论,人围观)参与讨论