評(píng)論和關(guān)注功能

1.數(shù)據(jù)庫(kù)t_follow的設(shè)計(jì):id,from_uid,to_uid1 4代表1號(hào)作者關(guān)注了4號(hào)用戶


t_folow.png

t_follow.data.png

2.高頻操作?實(shí)際項(xiàng)目如何處理干毅?
點(diǎn)贊循未,關(guān)注,喜歡搏存,統(tǒng)計(jì)閱讀量
先把數(shù)據(jù)存入緩存數(shù)據(jù)庫(kù)瑰步,然后使用定時(shí)任務(wù)持久化到底層數(shù)據(jù)庫(kù)

后端

  • entity:1.Follow
@Data
public class Follow {
    private Integer id;
    private Integer fromUId;
    private Integer toUId;
}

2.FollowVO對(duì)象視圖類(lèi)

@Data
public class FollowVO {
    private Integer toUId;
    private String nickname;
    private String avatar;
}```
3.mapper接口設(shè)計(jì)FollowMapper
insert方法,刪除記錄璧眠,根據(jù)fromID查所以缩焦,根據(jù)toid查所有,單一查(from,to)

public interface FollowMapper {

@Results({
        @Result(property = "id", column = "id"),
        @Result(property = "fromUId", column = "from_uid"),
        @Result(property = "toUId", column = "to_uid")
})
@Select("SELECT * FROM t_follow WHERE from_uid = #{fromUId} AND to_uid = #{toUId} ")
Follow getFollow(@Param("fromUId") int fromUId, @Param("toUId") int toUId);

@Results({
        @Result(property = "toUId", column = "to_uid"),
        @Result(property = "nickname", column = "nickname"),
        @Result(property = "avatar", column = "avatar")
})
@Select("SELECT a.to_uid,b.nickname,b.avatar FROM t_follow a LEFT JOIN t_user b ON a.to_uid = b.id WHERE a.from_uid = #{fromUId}  ")
List<FollowVO> getFollowsByUId(int fromUId);

@Insert("INSERT INTO t_follow (from_uid,to_uid) VALUES (#{fromUId},#{toUId}) ")
void insertFollow(Follow follow);

@Delete("DELETE  FROM t_follow WHERE from_uid = #{fromUId} AND to_uid = #{toUId} ")
void deleteFollow(@Param("fromUId") int fromUId, @Param("toUId") int toUId);

}

CommentMapper增加插入方法```
@Insert("INSERT INTO t_comment(u_id,a_id,content,comment_time) VALUES(#{uId}, #{aId}, #{content},#{commentTime}) ")
void insert(Comment comment);

4.service

  • FollowService
public interface FollowService {
    Follow getFollow(int fromUId, int toUId);

    List<FollowVO> getFollowsByUId(int fromUId);

    void insertFollow(Follow follow);

    void deleteFollow(int fromUId, int toUId);
}
  • CommentService
public interface CommentService {
    List<CommentVO> selectCommentsByAId(int aId);
    void addComment(Comment comment);
}

5.實(shí)現(xiàn)類(lèi)

  • FollowServiceImpl
package com.soft1721.jianyue.api.service.impl;

import com.soft1721.jianyue.api.entity.Follow;
import com.soft1721.jianyue.api.entity.VO.FollowVO;
import com.soft1721.jianyue.api.mapper.FollowMapper;
import com.soft1721.jianyue.api.service.FollowService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


@Service
public class FollowServiceImpl implements FollowService {
    @Resource
    private FollowMapper followMapper;

    @Override
    public Follow getFollow(int fromUId, int toUId) {

        return followMapper.getFollow(fromUId, toUId);
    }

    @Override
    public List<FollowVO> getFollowsByUId(int fromUId) {
        return followMapper.getFollowsByUId(fromUId);
    }

    @Override
    public void insertFollow(Follow follow) {
        followMapper.insertFollow(follow);

    }

    @Override
    public void deleteFollow(int fromUId, int toUId) {
        followMapper.deleteFollow(fromUId,toUId);
    }
}
  • CommentServiceImpl類(lèi)
package com.soft1721.jianyue.api.service.impl;

import com.soft1721.jianyue.api.entity.Comment;
import com.soft1721.jianyue.api.entity.VO.CommentVO;
import com.soft1721.jianyue.api.mapper.CommentMapper;
import com.soft1721.jianyue.api.service.CommentService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
@Service
public class CommentServiceImpl implements CommentService {

    @Resource
    private CommentMapper commentMapper;
    @Override
    public List<CommentVO> selectCommentsByAId(int aId) {

        return commentMapper.selectCommentsByAId(aId);
    }

    @Override
    public void addComment(Comment comment) {
        commentMapper.insert(comment);

    }
}

6.單元測(cè)試:

  • FollowServiceImplTest類(lèi)
package com.soft1721.jianyue.api.service.impl;

import com.soft1721.jianyue.api.entity.Follow;
import com.soft1721.jianyue.api.entity.VO.FollowVO;
import com.soft1721.jianyue.api.service.FollowService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class FollowServiceImplTest {
    @Resource
    private FollowService followService;

    @Test
    public void getFollow() {
        Follow followVO = followService.getFollow(1,4);
        System.out.println(followVO);
    }

    @Test
    public void getFollowsByUId() {
        List<FollowVO> followVO = followService.getFollowsByUId(1);
        System.out.println(followVO);
    }

    @Test
    public void insertFollow() {
        Follow follow = new Follow();
        follow.setFromUId(4);
        follow.setToUId(11);
        followService.insertFollow(follow);
    }

    @Test
    public void deleteFollow() {
        followService.deleteFollow(1,4);
    }
}
  • CommentService
package com.soft1721.jianyue.api.service.impl;

import com.soft1721.jianyue.api.entity.Comment;
import com.soft1721.jianyue.api.entity.VO.CommentVO;
import com.soft1721.jianyue.api.mapper.CommentMapper;
import com.soft1721.jianyue.api.service.CommentService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.List;

import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class CommentServiceImplTest {
    @Resource
    private CommentMapper commentMapper;
    @Resource
    private CommentService commentService;

    @Test
    public void selectCommentsByAId() {
        List<CommentVO> list = new ArrayList<>();
        list = commentMapper.selectCommentsByAId(1);
        System.out.println(list);
    }
    @Test
    public void addComment() {
        Comment comment = new Comment();
        comment.setAId(2);
        comment.setUId(4);
        comment.setContent("very good!");
        /* comment.setCommentTime(new Date(2019,04,10,9,43,35));*/
        commentService.addComment(comment);
    }

}

7.controller接口的獲取文章方法蛆橡,

  • FollowController
@RestController
@RequestMapping(value = "/api/follow")
public class FollowController {
    @Resource
    private FollowService followService;


    @PostMapping("/add")
    public ResponseResult followUser(@RequestParam("fromUId") int fromUId, @RequestParam("toUId") int toUId) {
        Follow follow = new Follow();
        follow.setFromUId(fromUId);
        follow.setToUId(toUId);
        followService.insertFollow(follow);
        return ResponseResult.success();
    }

    @PostMapping("/cancel")
    public ResponseResult cancelFollow(@RequestParam("fromUId") int fromUId, @RequestParam("toUId") int toUId) {
        followService.deleteFollow(fromUId, toUId);
        return ResponseResult.success();
    }
}
  • CommentController類(lèi)
@RestController
@RequestMapping(value = "/api/comment")
public class CommentController {
    @Resource
    private CommentService commentService;

    @PostMapping("/add")
    public ResponseResult addComment(@RequestParam("aId") int aId, @RequestParam("uId") int uId, @RequestParam("content") String content) {
        Comment comment = new Comment();
        comment.setAId(aId);
        comment.setUId(uId);
        comment.setContent(content);
        comment.setCommentTime(new Date());
        commentService.addComment(comment);
        return ResponseResult.success();
    }
}

修改一下ArticleController接口中的根據(jù)id獲取文章的方法舌界,增加一個(gè)參數(shù):登錄用戶的id,來(lái)判斷登錄用戶是否已經(jīng)關(guān)注了文章作者

@GetMapping(value = "/{aId}")
public ResponseResult getArticleById(@PathVariable("aId") int aId,@RequestParam("userId") int userId) {
    ArticleVO article = articleService.getArticleById(aId);
    int toUId = article.getUId();
    Map<String, Object> map = new HashMap<>();
    Follow follow = followService.getFollow(userId, toUId);
    if (follow != null) {
        map.put("followed", MsgConst.FOLLOWED);
    } else {
        map.put("followed", MsgConst.NO_FOLLOWED);
    }
    List<CommentVO> comments = commentService.selectCommentsByAId(aId);
    map.put("article", article);
    map.put("comments", comments);
    return ResponseResult.success(map);
}

前端代碼:

article_detail.vue

<template>
    <view class="container">
        <text class="article-title">{{ article.title }}</text>
        <view class="article-info">
            <image :src="article.avatar" class="avatar small"></image>
            <text class="nickname">{{ article.nickname }}</text>
            <!-- <text class="info-text">{{ handleTime(article.createTime) }}</text> -->
            <text>{{article.createTime}}</text>
            <!-- 登錄用戶和文章作者不是同一個(gè)人泰演,就顯示關(guān)注或取消關(guān)注按鈕 -->
            <button v-if="userId != article.uId && !followed" class="follow-btn" @tap="follow">關(guān)注</button>
            <button v-if="userId != article.uId && followed" class="follow-btn cancel" @tap="cancelFollow">取消</button>
        </view>

        <view class="grace-text" style="margin-top: 10px;"><rich-text :nodes="article.content" bindtap="tap"></rich-text>
        <button v-if="userId != article.uId && !liked" class="follow-btn1" @tap="like">
            <image src="../../static/heart1.png"></image>
        </button>
        <button v-if="userId != article.uId && liked" class="follow-btn1 cancel" @tap="cancelLike">
            <image src="../../static/heart.png"></image>
        </button>
        </view>
        <text class="info-text">評(píng)論{{ comments.length }}</text>
        <view class="comment-item" v-for="(comment, index) in comments" :key="index">
            <view class="left"><image :src="comment.avatar" class="avatar small"></image></view>
            <view class="right">
                <text>{{ comment.nickname }}</text>
                <text>{{ comment.content }}</text>
                <view>
                    <text style="margin-right: 10px;">{{ comments.length - index }}樓</text>
                    <!-- <text>{{ handleTime(comment.commentTime) }}</text> -->
                    <text>{{comment.commentTime}}</text>
                </view>
            </view>
        </view>
        <input class="uni-input comment-box" type="text" placeholder="寫(xiě)下你的評(píng)論" v-model="content" required="required" />
        <button class="green-btn" @tap="send">提交</button>
    </view>
</template>

<script>
export default {
    data() {
        return {
            article: {
                aId: 0,
                uId: 0,
                title: '',
                content: '',
                avatar: '',
                nickname: '',
                createTime: ''
            },
            comments: [],
            content: '',
            userId: uni.getStorageSync('login_key').userId,
            followed: false,
            liked:false
        };
    },
    onLoad: function(option) {
        //option為object類(lèi)型呻拌,會(huì)序列化上個(gè)頁(yè)面?zhèn)鬟f的參數(shù)
        this.article.aId = option.aId;
    },
    onShow: function() {
        this.getArticle();
    },
    onPullDownRefresh: function() {
        this.getArticle();
    },
    methods: {
        getArticle: function() {
            var _this = this;
            uni.request({
                url: this.apiServer + '/article/' + this.article.aId,
                method: 'GET',
                header: { 'content-type': 'application/x-www-form-urlencoded' },
                data: {
                    userId: this.userId
                },
                success: res => {
                    console.log(res.data.data.article);
                    _this.article.aId = res.data.data.article.id;
                    _this.article.uId = res.data.data.article.uid;
                    _this.article.title = res.data.data.article.title;
                    _this.article.content = res.data.data.article.content;
                    _this.article.nickname = res.data.data.article.nickname;
                    _this.article.avatar = res.data.data.article.avatar;
                    _this.article.createTime = res.data.data.article.createTime;
                    _this.comments = res.data.data.comments;
                    if (res.data.data.followed === '已關(guān)注') {
                        _this.followed = true;
                        _this.liked=true;
                    }
                },
                complete: function() {
                    uni.stopPullDownRefresh();
                }
            });
        },
        handleTime: function(date) {
            var d = new Date(date);
            var year = d.getFullYear();
            var month = d.getMonth() + 1;
            var day = d.getDate() < 10 ? '0' + d.getDate() : '' + d.getDate();
            var hour = d.getHours() < 10 ? '0' + d.getHours() : '' + d.getHours();
            var minutes = d.getMinutes() < 10 ? '0' + d.getMinutes() : '' + d.getMinutes();
            var seconds = d.getSeconds() < 10 ? '0' + d.getSeconds() : '' + d.getSeconds();
            return year + '-' + month + '-' + day + ' ' + hour + ':' + minutes + ':' + seconds;
        },
        send: function() {
            console.log('評(píng)論人編號(hào):' + this.userId + ',文章編號(hào):' + this.article.aId + ',評(píng)論內(nèi)容:' + this.content);
            uni.request({
                url: this.apiServer + '/comment/add',
                method: 'POST',
                header: { 'content-type': 'application/x-www-form-urlencoded' },
                data: {
                    aId: this.article.aId,
                    uId: this.userId,
                    content: this.content
                },
                success: res => {
                    if (res.data.code === 0) {
                        uni.showToast({
                            title: '評(píng)論成功'
                        });
                        this.getArticle();
                        this.content = '';
                    }
                }
            });
        },
        follow:function(){
            uni.request({
                url: this.apiServer + '/follow/add',
                method: 'POST',
                header: { 'content-type': 'application/x-www-form-urlencoded' },
                data: {
                    fromUId: this.userId,
                    toUId: this.article.uId
                },
                success: res => {
                    if (res.data.code === 0) {
                        uni.showToast({
                            title: '關(guān)注成功'
                        });
                        this.followed = true;
                    }
                }
            });
        },
        like:function(){
            uni.request({
                url: this.apiServer + '/like/add',
                method: 'POST',
                header: { 'content-type': 'application/x-www-form-urlencoded' },
                data: {
                    fromId: this.userId,
                    toId: this.article.uId
                },
                success: res => {
                    if (res.data.code === 0) {
                        uni.showToast({
                            title: '喜歡'
                        });
                        this.liked = true;
                    }
                }
            });
        },
        cancelFollow:function(){
            uni.request({
                url: this.apiServer + '/follow/cancel',
                method: 'POST',
                header: { 'content-type': 'application/x-www-form-urlencoded' },
                data: {
                    fromUId: this.userId,
                    toUId: this.article.uId
                },
                success: res => {
                    if (res.data.code === 0) {
                        uni.showToast({
                            title: '已取消關(guān)注'
                        });
                        this.followed = false;
                    }
                }
            });
        },
        cancelLike:function(){
            uni.request({
                url: this.apiServer + '/like/cancel',
                method: 'POST',
                header: { 'content-type': 'application/x-www-form-urlencoded' },
                data: {
                    fromId: this.userId,
                    toId: this.article.uId
                },
                success: res => {
                    if (res.data.code === 0) {
                        uni.showToast({
                            title: ''
                        });
                        this.liked = false;
                    }
                }
            });
        }
    }
};
</script>

<style>
.content {
    margin-bottom: 10px;
    margin-top: 10px;
    padding: 5px;
    border-bottom: 1px solid #eee;
}
.img-list {
    display: flex;
    flex-direction: column;
}
.img-item {
    width: 100%;
    height: 150px;
    margin-bottom: 5px;
}
.img-item image {
    width: 100%;
    height: 100%;
    border-radius: 5px;
}
.comment-item {
    display: flex;
    align-items: center;
    border-bottom: 1px solid #eee;
    margin-bottom: 10px;
    padding: 5px;
}
.comment-item .left {
    flex: 1 1 15%;
}
.comment-item .right {
    flex: 1 1 85%;
    display: flex;
    flex-direction: column;
}
.comment-box {
    /* border: 1px solid #fff;
    border-radius: 5px;
    background-color: #eee;
    height: 50upx; */
    margin-top: 20upx;
}
.follow-btn {
    height: 33px;
    width: 80px;
    font-size: 12pt;
    text-align: center;
    padding-bottom: 20px;
    margin-right: 0px;
    background: #10AEFF;
    color: #fff;
}
.cancel{
    background-color: #aaa;
}
.green-btn{
    background: #10AEFF;
    color: #fff;
}
.article-title{
    font-size: 40upx;
    font-weight: 700;
}
.grace-text{
    font-weight: 500;
    font-size: 40upx;
    border-bottom:10px solid #fff;
}
.article-info{
    display: flex;
    border-top:70upx solid #FFFFFF;
}
.follow-btn1{
    width: 200upx;
    height: 100upx;
    background: #fff;
}
.follow-btn1 image{
    width: 100upx;
    height: 50upx;
}
</style>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末睦焕,一起剝皮案震驚了整個(gè)濱河市藐握,隨后出現(xiàn)的幾起案子靴拱,更是在濱河造成了極大的恐慌,老刑警劉巖猾普,帶你破解...
    沈念sama閱讀 216,372評(píng)論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件袜炕,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡初家,警方通過(guò)查閱死者的電腦和手機(jī)偎窘,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,368評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)溜在,“玉大人陌知,你說(shuō)我怎么就攤上這事∫蠢撸” “怎么了仆葡?”我有些...
    開(kāi)封第一講書(shū)人閱讀 162,415評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)志笼。 經(jīng)常有香客問(wèn)我沿盅,道長(zhǎng),這世上最難降的妖魔是什么纫溃? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,157評(píng)論 1 292
  • 正文 為了忘掉前任腰涧,我火速辦了婚禮,結(jié)果婚禮上皇耗,老公的妹妹穿的比我還像新娘南窗。我一直安慰自己,他們只是感情好郎楼,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,171評(píng)論 6 388
  • 文/花漫 我一把揭開(kāi)白布万伤。 她就那樣靜靜地躺著,像睡著了一般呜袁。 火紅的嫁衣襯著肌膚如雪敌买。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,125評(píng)論 1 297
  • 那天阶界,我揣著相機(jī)與錄音虹钮,去河邊找鬼。 笑死膘融,一個(gè)胖子當(dāng)著我的面吹牛芙粱,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播氧映,決...
    沈念sama閱讀 40,028評(píng)論 3 417
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼春畔,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起律姨,我...
    開(kāi)封第一講書(shū)人閱讀 38,887評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤振峻,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后择份,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體扣孟,經(jīng)...
    沈念sama閱讀 45,310評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,533評(píng)論 2 332
  • 正文 我和宋清朗相戀三年荣赶,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了凤价。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,690評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡讯壶,死狀恐怖料仗,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情伏蚊,我是刑警寧澤,帶...
    沈念sama閱讀 35,411評(píng)論 5 343
  • 正文 年R本政府宣布格粪,位于F島的核電站躏吊,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏帐萎。R本人自食惡果不足惜比伏,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,004評(píng)論 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望疆导。 院中可真熱鬧赁项,春花似錦、人聲如沸澈段。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,659評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)败富。三九已至悔醋,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間兽叮,已是汗流浹背芬骄。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,812評(píng)論 1 268
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留鹦聪,地道東北人账阻。 一個(gè)月前我還...
    沈念sama閱讀 47,693評(píng)論 2 368
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像泽本,于是被迫代替她去往敵國(guó)和親淘太。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,577評(píng)論 2 353

推薦閱讀更多精彩內(nèi)容