// +---------------------------------------------------------------------- declare (strict_types = 1); namespace addon\articles\model; use ywxapp\model\BaseModel; /** * 附件模型 * * 记录通过上传接口产生的文件(图片/文档等),便于后台统一查看与清理。 * 文件本身由框架 FileStorageService 落盘,这里只存元数据。 */ class ArticleAttachment extends BaseModel { protected $name = 'articles_attachment'; protected $autoWriteTimestamp = false; protected $type = [ 'uid' => 'integer', 'size' => 'integer', 'aid' => 'integer', ]; /** * 记录一次上传 * * @param array $file 上传结果(含 url/path/size/mime 等,字段缺失时自动降级) * @param int $uid 上传者 * @param int $aid 关联文章ID(0=未关联) */ public static function record(array $file, int $uid = 0, int $aid = 0): self { $url = (string) ($file['url'] ?? $file['path'] ?? ''); $name = (string) ($file['name'] ?? basename($url)); return self::create([ 'uid' => $uid, 'name' => $name, 'url' => $url, 'path' => (string) ($file['path'] ?? ''), 'ext' => strtolower(pathinfo($name, PATHINFO_EXTENSION)), 'mime' => (string) ($file['mime'] ?? ''), 'size' => (int) ($file['size'] ?? 0), 'aid' => $aid, 'create_at' => time(), ]); } /** * 人类可读大小 */ public function getSizeTextAttr(): string { $size = (int) ($this->size ?? 0); if ($size < 1024) { return $size . ' B'; } if ($size < 1048576) { return round($size / 1024, 1) . ' KB'; } return round($size / 1048576, 2) . ' MB'; } public static function ensureSchema(): void { \addon\articles\library\ArticleSchema::ensure(); } }