本文实例讲述了tp5.0框架实现无限极回复功能的方法。分享给大家供大家参考,具体如下:

最近做项目的时候用到了评论回复,使用thinkphp5.0框架做回复碰到了一些问题,简单总结一下。(李昌辉)

1.首先是数据表的设计:

create table zy_huifu
(
  code int auto_increment primary key, #回复代号
  puser varchar(50), #回复人员
  listcode int, #文章代号
  time varchar(50), #回复时间
  content text, #回复内容
  pcode int, #父级代号 0文章
  leval int, #级别 0顶级 1其它
  isok int #已读未读0未读1已读
);

评论和回复放在了一张表里面,为了在显示的时候做区分,评论作为顶级回复级别代号为0,其它的子级回复级别代号为1。

每个回复都有一个父级代号代表回复的哪一条评论,如果是直接评论的文章,父级代号设置为0.

2.接下来是在页面上显示评论和回复信息:

在控制器里面,我们需要去查询该文章下的所有评论及回复内容,并且注册到tp框架里面,这里调用了一个方法commentlist()来获取该文章下的评论回复:

//查询评论
$ahuifu = $this->commentlist($code,0);
$this->assign("ahuifu",$ahuifu);

commentlist()方法如下,使用递归的方式将所有评论回复按照一定的顺序查询出来并且存储到数组里面:

//读取评论列表的递归,code为文章代号,pcode为父级代号
  public function commentlist($code,$pcode){
    $commentlist = array(); //存储评论数组
    $list = db::table("zy_huifu")
    ->alias('a')
    ->where("listcode",$code)
    ->where("pcode",$pcode)
    ->join("zy_user b","a.puser = b.uid")
    ->select();
    foreach($list as $v){
      $commentlist[] = $v;
      //查询子回复
      $zi = $this->commentlist($code,$v["code"]);
      if(count($zi)){
        foreach($zi as $v1){
          $commentlist[] = $v1;
        }
      }
    }
    return $commentlist;
  }

在view视图页面显示数据:

{volist name="ahuifu" id="vp"}
        {if condition="($vp.leval == 0)"}
        <div class="panel panel-default pl_list">
        <div class="panel-body pl_list_nr">
          <div class="show_nr_pl_tou">
            <img src="{$vp.img}" width="30" height="30" />  
            <span>{$vp.name}</span> 
            <span>{$vp.time|date="y-m-d h:i:s",###}</span> 
            <span><button class="btn btn-primary btn-xs show_huifu_btn" pcode="{$vp.code}">回复</button></span>
          </div>
          <div class="show_nr_pl_nr">
            {$vp.content}
          </div>
        </div>
        </div>
        {else /}
        <div class="panel panel-default pl_list">
        <div class="panel-body pl_list_nr" style="margin-left:50px">
          <div class="show_nr_pl_tou">
            <img src="{$vp.img}" width="30" height="30" />  
            <span>{$vp.name}</span> 
            <span>{$vp.time|date="y-m-d h:i:s",###}</span> 
            <span><button class="btn btn-primary btn-xs show_huifu_btn" pcode="{$vp.code}">回复</button></span>
          </div>
          <div class="show_nr_pl_nr">
            {$vp.content}
          </div>
        </div>
        </div>
        {/if}
{/volist}

3.添加回复及评论

添加评论的时候注意将父级代号pcode添加为0,将级别leval添加为0即可。

添加回复的时候将父级代号添加为要回复的这一条数据的主键,将级别leval添加为1即可。

具体实现比较简单,不赘述。

更多关于thinkphp相关内容感兴趣的读者可查看本站专题:《thinkphp入门教程》、《thinkphp模板操作技巧总结》、《thinkphp常用方法总结》、《codeigniter入门教程》、《ci(codeigniter)框架进阶教程》、《zend framework框架入门教程》及《php模板技术总结》。

希望本文所述对大家基于thinkphp框架的php程序设计有所帮助。