PHP無限級評論回覆功能實現

闖進華府的9527發表於2020-11-14
protected  function commentList($aid,$pid = 0,&$result=array()){
$arr = ArticleComment::relation(['usertalent'=> function($query){
$query->field('id,talent_usernickname,talent_avatar');
}])->where(['pid' => $pid])->where(['article_id' => $aid])->order('id desc')->select();
if(empty($arr)){
return array();
}
foreach ($arr as $cm) {
$thisArr=&$result[];
$cm["children"] = $this->commentList($aid,$cm["id"],$thisArr);
$thisArr = $cm;
}
return $result;
}

呼叫方法
$this->commentList($aid);

專案中使用tp5寫文章評論回覆功能
表中使用pid來標識回覆表的id 表結構如下

CREATE TABLE `bcpub_article_comment` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`author_id` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '作者ID',
`article_id` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '文章ID',
`pid` int(11) unsigned NOT NULL DEFAULT '0',
`uid` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '評論人ID',
`comment` varchar(250) NOT NULL DEFAULT '',
`give_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '評論點贊數量',
`add_time` int(10) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `author_id` (`author_id`),
KEY `pid` (`pid`)
) ENGINE=MyISAM AUTO_INCREMENT=97 DEFAULT CHARSET=utf8 COMMENT='文章評論表'

相關文章