分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 前端开发

Thinkphp关联模型使用

发布时间:2023-09-06 01:16责任编辑:苏小强关键词:暂无标签

1.需求描述

首页文章列表,需要同时获取文章的点赞和被关注数,同时如果被当前用户点赞或关注了会显示相应小图标进行区别。图示如下:

2.解决方案

数据库设计:

文章对应Article表,其中包括收藏数字段fav,点赞数字段zan

中间表user_fav,user_zan分别表示某一用户对某篇文章的点赞与收藏, 其中包括userid,usertype,article_id等字段

TP5代码实现部分:

框架用的TP5,参考开发手册其中关联模型部分,在article模型中增加userFav和userZan方法

 ???public function userFav() ???{ ???????return $this->hasMany(‘UserFav‘,‘article_id‘)->field(‘userid‘); ???} ???public function userZan() ???{ ???????return $this->hasMany(‘UserZan‘,‘article_id‘)->field(‘userid‘); ???}

Controller中index方法显示文章列表

 ???public function index($page=1) ???{ ???????// $this->articlemodel = new Article(); ???????// $list = $this->articlemodel->where(‘schoolid‘,$user[‘schoolid‘])->where(‘classid‘,$user[‘classid‘])->group(‘create_time‘)->select(); ???????$list = $this->articlemodel->withCount([‘userzan‘=>function($query){ ???????????$query->where(‘userid‘,cookie(‘userid‘))->where(‘usertype‘,cookie(‘usertype‘)); ???????}])->order(‘zan desc,is_top desc,is_recommend desc,id desc‘)->paginate(5,false,[‘page‘ => $page]); ???????????????$this->assign(‘list‘, $list); ???????????????return $this->fetch(); ???}

View中获取点赞数关注数同时判断如果当前用户点赞,部分代码

 ???{volist name="list" id="vo"} ???<div class="in_parent"> ???????<img src="{$vo[‘photo‘][0]}" data-id="{$vo[‘id‘]}"> ???????<div class="in_par_con"> ???????????<p>{$vo.title}</p> ???????</div> ???????<div class="in_par_con"> ?????????{foreach :explode(‘,‘,$vo[‘tags‘]) as $tag} ???????????<span>{$tag}</span> ???????????{/foreach} ???????</div> ???????<div class="in_per"> ???????????<div class="in_per_lf fl"> ???????????????<img src="__H5IMAGES__/pic.png" class="fl"/> ???????????????<div class="fl ml5 mt10">{$vo.author}<p class="gray">{php}echo date(‘Y-m-d‘,strtotime($vo[‘create_time‘]));{/php}</p></div> ???????????</div> ???????????<div class="in_per_rt fr"> ???????????????<span class="gray fr mt30 ml3 care-val">收藏 {$vo.fav}</span> ???????????????<div class="fr mt30 ml3 care{eq name=‘$vo.userfav_count‘ value=‘1‘} care01{/eq}" data-id="{$vo.id}"></div> ???????????????<span class="gray fr mt30 ml3 zan-val">{$vo.zan}</span> ???????????????<div class="fr mt30 ml3 zan{eq name=‘$vo.userzan_count‘ value=‘1‘} zan01{/eq}" data-id="{$vo.id}"></div> ???????????</div> ???????????<div class="clear"></div> ???????</div> ???</div> ???{/volist}

php用的时间不长,用的不对的地方望不吝赐教

Thinkphp关联模型使用

原文地址:http://www.cnblogs.com/s1ihome/p/7642681.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved