当查看问题详情的时候,展示含有相同标签的问题为相关问题
后端逻辑
- 使用正则来查询符合条件的数据。在QuestionExtMapper中添加方法
List<Question> selectRelated(Question record);
<select id="selectRelated" parameterType="com.july.community.model.Question" resultMap="BaseResultMap">
select * from tbl_question where id != #{id} and tag regexp #{tag}
</select>
- 编写逻辑
questionController
//获取相关问题
List<QuestionDTO> relatedQuestionDTOs = questionService.getRelated(questionDTO);
model.addAttribute("relatedQuestionList",relatedQuestionDTOs);
questionService
//获取相关问题
public List<QuestionDTO> getRelated(QuestionDTO questionDTO) {
if (StringUtils.isBlank(questionDTO.getTag())){
//若该问题没有tag,就没有相关问题
return new ArrayList<>();
}
//将tag中的,替换成|以供正则使用
StringUtils.replace(questionDTO.getTag(),",","|");
System.out.println(questionDTO.getTag());
Question question = new Question();
question.setId(questionDTO.getId());
question.setTag(questionDTO.getTag());
List<Question> relatedQuestions = questionExtMapper.selectRelated(question);
List<QuestionDTO> relatedQuestionDTOs = relatedQuestions.stream().map(q -> {
QuestionDTO relatedQuestionDTO = new QuestionDTO();
BeanUtils.copyProperties(q,relatedQuestionDTO);
return relatedQuestionDTO;
}).collect(Collectors.toList());
return relatedQuestionDTOs;
}
前端展示
- 标签展示前端
<!--展示标签-->
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<span class="label label-info question-tag" th:each=" tag : ${question.tag.split(',')}">
<span class="glyphicon glyphicon-tag"></span>
<span class="label label-info" th:text="${tag}"></span>
</span>
</div>
- 相关问题的展示
<!--相关问题部分-->
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<h4>相关问题</h4>
<ul class="question-related">
<li th:each="relatedQuestion : ${relatedQuestionList}">
<a th:href="@{'/question/' + ${relatedQuestion.id}}" th:text="${relatedQuestion.title}"></a>
</li>
</ul>
</div>
</div>
.question-tag{
margin-right: 5px;
}
.question-related{
line-height: 20px;
font-size: 12px;
margin-left: 0;
list-style: none;
padding-left: 0;
}