// +---------------------------------------------------------------------- declare (strict_types = 1); namespace addon\blog\model; use think\facade\Db; use ywxapp\model\BaseModel; use ywxapp\model\MemberUser; class BlogComment extends BaseModel { // 设置数据表名 protected $name = 'blog_comment'; // 设置主键 protected $pk = 'id'; // 自动写入时间戳(int 型 Unix 时间戳,匹配 create_at/update_at int 列) protected $autoWriteTimestamp = 'int'; protected $createTime = 'create_at'; protected $updateTime = 'update_at'; // 定义允许写入的字段 protected $allowField = [ 'content', 'uid', 'aid', 'pid', 'status', 'like_count', 'ip', 'user_agent', ]; // 设置字段类型 protected $type = [ 'id' => 'int', 'uid' => 'int', 'aid' => 'int', 'pid' => 'int', 'status' => 'int', 'like_count' => 'int', 'create_at' => 'int', 'update_at' => 'int', ]; // 内容修改器(过滤敏感词) public function setContentAttr($value) { $sensitiveWords = ['垃圾', '广告', '违法', '政治']; return str_replace($sensitiveWords, '***', $value); } // 定义关联 - 用户(博客用户即主系统会员,统一使用 wxapp_user 表,主键 uid) public function user() { return $this->belongsTo(MemberUser::class, 'uid', 'uid'); } // 定义关联 - 文章 public function article() { return $this->belongsTo(BlogArticle::class, 'aid'); } // 定义关联 - 子评论 public function children() { return $this->hasMany(BlogComment::class, 'pid'); } // 定义关联 - 父评论 public function parent() { return $this->belongsTo(BlogComment::class, 'pid'); } // 检查评论是否通过审核 public function isApproved() { return $this->status === 1; } // 格式化创建时间(兼容 int / 数字字符串 / 日期字符串 / DateTime) public function getCreateTextAttr($value, $data) { $t = $data['create_at'] ?? $value; if ($t instanceof \DateTime) { return $t->format('Y-m-d H:i'); } if (is_numeric($t)) { return date('Y-m-d H:i', (int) $t); } $ts = strtotime((string) $t); return $ts !== false ? date('Y-m-d H:i', $ts) : (string) $t; } // 获取评论树 public static function getCommentTree($articleId, $parentId = 0, $depth = 0) { $comments = self::with('member') ->where('aid', $articleId) ->where('pid', $parentId) ->where('status', 1) ->order('create_at', 'asc') ->select(); $tree = []; foreach ($comments as $comment) { $comment->depth = $depth; $comment->children = self::getCommentTree($articleId, $comment->id, $depth + 1); $tree[] = $comment; } return $tree; } // 删除评论及其子评论 public function deleteWithChildren() { // 删除子评论 $children = $this->children()->select(); foreach ($children as $child) { $child->deleteWithChildren(); } // 删除当前评论 $this->delete(); // 更新文章评论数 Db::name('blog_article') ->where('id', $this->aid) ->dec('comment_count') ->update(); } }