平台是:codeigniter。
我在数据库中有一行评论,其中包含对广告的所有评论。 评论行有ID、广告ID、评论、评论回复:
我的问题是对广告的重复评论,因此如果用户对广告发表评论,脚本将回复他文字“感谢评论”。
如您所见(随机用户可以对我的广告发表评论) commenter_id = 112 是多次评论,会导致服务器过载。
我的代码是这样的:
$comment_list = $this->basic->get_all_comment_of_ads($adsid);
$commenter_count=isset($comment_list["commenter_info"]) ? count($comment_list["commenter_info"]) : 0 ;
if(isset($comment_list["commenter_info"]))
{
if(isset($comment_list["commenter_info"][$ad_account_id]))
{
$commenter_count--; // if ad account is also commenter
unset($comment_list["commenter_info"][$ad_account_id]);
}
}
因此,本例中的结果
$commenter_count
将为 3(5 - 2 个重复)。
如何防止对同一 commenter_id 的评论进行回复?
我尝试这样做:
$i=0;
$commenter_info=array();
foreach($comment_list as $info){
$time= isset($info['created_time'])?(array)$info['created_time']:"";
$comment_info[$i]['created_time']=isset($time['date'])?$time['date']:"";
$comment_info[$i]['commenter_name']=isset($info['from']['name'])? $info['from']['name']:"";
$comment_info[$i]['commenter_id']=isset($info['from']['id'])?$info['from']['id']:"";
$comment_info[$i]['message']=isset($info['commente_text'])?$info['message']:"";
$comment_info[$i]['comment_id']=isset($info['id'])?$info['id']:"";
/* Store Commenter info as unique */
if(!isset($commenter_info[$comment_info[$i]['commenter_id']])){
$commenter_info[$comment_info[$i]['commenter_id']]['name']=$comment_info[$i]['commenter_name'];
$commenter_info[$comment_info[$i]['commenter_id']]['last_comment']=$comment_info[$i]['message'];
$commenter_info[$comment_info[$i]['commenter_id']]['last_comment_id']=$comment_info[$i]['comment_id'];
$commenter_info[$comment_info[$i]['commenter_id']]['last_comment_time']=$comment_info[$i]['created_time'];
}
$i++;
}
但它将返回到评论者计数 (3)。
我在这一点上停了下来,我无法获得如何获取commenter_id并存储它以检查commenter_id是否重复并且在第一次回复后不再回复他的逻辑。
我查看了大多数回复,但这对我的情况没有帮助。
我相信您所追求的答案是
UNIQUE
列上的 commenter_id
索引(假设是 MySQL)。假设您使用的是 Codeigniter 4,您可以执行以下操作:
$db = $this->db->table('comments');
$db->set([
'commenter_id' => '',
'adsid' => '',
'commente_text' => '',
'response_to_text' => ''
]);
$db->ignore(true);
$db->insert();
注意你的
ignore(true)
是这里的关键。这在 mysql 中做了类似的事情:
INSERT IGNORE INTO comments ...
因此,如果用户已经添加了评论(即,基本上会忽略该行) 具有相同 DB Key 的元素)。但是您应该考虑到用户可能想要
update
他们的评论!在这种情况下,您可以调用 update()
函数并使用 WHERE
来更新记录而不是忽略它。