// +---------------------------------------------------------------------- declare (strict_types = 1); namespace addon\articles\model; use think\facade\Db; use think\model\Pivot; use ywxapp\model\BaseModel; /** * 专题-文章关联模型 */ class ArticleTopicArticle extends Pivot { protected $name = 'articles_topic_article'; public $autoWriteTimestamp = false; /** * 某专题下的文章ID(按专题内排序) */ public static function articleIdsOf(int $tid): array { if ($tid <= 0) { return []; } return self::where('tid', $tid)->order('sort', 'asc')->order('aid', 'desc')->column('aid'); } /** * 某文章所属的专题ID */ public static function topicIdsOf(int $aid): array { if ($aid <= 0) { return []; } return self::where('aid', $aid)->column('tid'); } /** * 同步专题下的文章(先删后插,事务保护) * * @param int $tid 专题ID * @param array $aids 文章ID数组(顺序即专题内排序) */ public static function syncArticles(int $tid, array $aids): void { Db::transaction(function () use ($tid, $aids) { self::where('tid', $tid)->delete(); $data = []; $sort = 0; foreach ($aids as $aid) { $aid = (int) $aid; if ($aid <= 0) { continue; } $data[] = ['tid' => $tid, 'aid' => $aid, 'sort' => $sort++]; } if ($data) { self::insertAll($data); } }); } }