如何解决如何获取集合关系中的总项目
我有一个生成类别树的函数: 我想计算父类别中存在多少帖子,包括所有级别的子类别。我创建了一个只计算两个级别的代码。但我希望它支持无限级别。
private function buildMenu(): void
{
$this->menu = new Collection();
$this->postCategories = PostCategory::with('posts')->orderBy('order')->get();
foreach ($this->postCategories as $postCategory) {
if ($postCategory->isTopLevelParent()) {
$subChildren = $this->getChildren($postCategory,1);
$this->menu->push(new MenuItem([
'count' => $this->countPosts($postCategory,$subChildren),'children' => $subChildren,'offset' => 0,'category' => null,]));
}
}
$this->menu->prepend(new MenuItem([
'count' => $this->getAllPostCount(),'children' => collect([]),]));
}
private function getChildren(PostCategory $parentCategory,int $offset): Collection
{
$children = collect([]);
foreach ($this->postCategories as $postCategory) {
if ($postCategory->parent_id === $parentCategory->id) {
$subChildren = $this->getChildren($postCategory,$offset + 1);
$children->push(new MenuItem([
'count' => $this->countPosts($postCategory,'offset' => $offset,'category' => $postCategory,]));
}
}
return $children;
}
private function countPosts(PostCategory $postCategory,Collection $children): int
{
$postIds = $postCategory->posts->pluck('id')->toArray();
foreach ($children as $child) {
$postIds = array_merge($postIds,$child->category->posts->pluck('id')->toArray());
$child->category = null;
}
return count(array_unique($postIds));
}
我有 post_categories 表,其中有 ID 和 PARENT ID。
然后我有一个名为 post_category 的表,其中有 post_id 和 category_id
最后我有 POSTS 表,其中 POSTS.ID 与 POST_CATEGORY 表中的 POST_ID 有关系。
邮政类别模型。我已经从模型中删除了未使用的功能,否则我无法编辑问题
class PostCategory extends Model implements HasMedia
{
public function posts()
{
return $this->belongsToMany(Post::class,'post_category','category_id','post_id');
}
public function featuredPosts()
{
return $this->belongsToMany(Post::class,'post_category_featured','post_id');
}
public function children()
{
return $this->hasMany(PostCategory::class,'parent_id')->orderBy('name');
}
public function parent()
{
return $this->belongsTo(PostCategory::class,'parent_id');
}
public function isTopLevelParent(): bool
{
return $this->parent_id === null;
}
public static function withChildren(): Builder
{
return self::with('children.children.children.children.children.children.children');
}
}
在此先感谢您!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。