Thinkphp关联模型使用

1.需求描述php

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

2.解决方案cookie

数据库设计:框架

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

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

TP5代码实现部分:this

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

    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中获取点赞数关注数同时判断若是当前用户点赞,部分代码code

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