zoukankan      html  css  js  c++  java
  • Thinkphp关联模型使用

    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用的时间不长,用的不对的地方望不吝赐教

  • 相关阅读:
    外键的缺陷
    laravel 关联模型
    n的阶乘末尾出现的次数
    JavaScript的self和this使用小结
    cocos2dx中的内存管理方式
    c++ 与 lua 简单交互参数介绍
    c++的单例模式及c++11对单例模式的优化
    cocos2dx帧动画
    cocos2dx中坐标系
    cocos2dx中替代goto的用法:do{}while(0)和CC_BREAK_IF
  • 原文地址:https://www.cnblogs.com/s1ihome/p/7642681.html
Copyright © 2011-2022 走看看