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

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']);
}
文章详情展示页面中输出浏览统计数据

统计数据页面展示效果

