laravel 获取所有孩子的父母关系船

时间:2021-01-15 14:52:10

标签: php laravel relationship

在我们使用 laravel 的应用程序中,我们使用数据库关系实现了父子结构。例如:

所有 ID 都是此结构中的示例:

programmings (NULL):
    web programmings (1)
       backend (2)
           laravel (3)
       api )4)
           lumen (5)
       python (6)
    desktop (7)
       java (8)

我们数据库中的每个父级都以 null 开头并指向,并且每个子级都有父级 ID。现在,当我们尝试获取 laravel 的所有父母时,我们应该:

backend - web programmings - programmings 

Category 模型结构:

/**
 * Get the parent Category to which the current Category belongs.
 */
public function parent(): BelongsTo
{
    return $this->belongsTo(Category::class, 'parent_id', 'id', 'parent');
}

/**
 * Get all Categories which belong to the current Category.
 */
public function subcategories(): HasMany
{
    return $this->hasMany(Category::class, 'parent_id', 'id');
}

我获得了一个级别的孩子父母,但我不知道如何才能让所有孩子的父母到达null

根据角色获取所有帖子:

控制器:

$categories = auth()->user()->availableCategories();

HasPosts 特性:

trait HasCategories
{
    public function availableCategories(): Collection
    {
        $categories = $this->categories;

        $parents = $categories->filter(function ($cat) use ($categories) {
            return !in_array($cat->parent_id, $categories->pluck('id')->all()) || is_null($cat->parent_id);
        });

        $parents->map(
            fn ($parent) => $this->setNested($parent, $categories)
        );

        return $parents;
    }

    /**
     * Get all Categories with Posts associated with the User in nested tree structure.
     */
    public function availableCategoriesWithPosts(): Collection
    {
        $categories = $this->categories()->withPosts()->get();

        $parents = $categories->filter(
            fn ($cat) =>
            !$categories->contains('id', $cat->parent_id) || is_null($cat->parent_id)
        );

        $parents->map(fn ($parent) => $this->setNested($parent, $categories));

        return $parents;
    }
        
           
    protected function setNested($parent, $categories)
    {
        $parent->setRelation('subcategories', $categories->where('parent_id', $parent->id));
        $parent->subcategories->map(function ($sub) use ($categories) {
            if ($categories->contains('parent_id', $sub->id)) {
                $this->setNested($sub, $categories);
                return $sub;
            }
        });
    }
}

我试试这个代码:

public function parent(): BelongsTo
{
    return $this->belongsTo(Category::class, 'parent_id', 'id', 'parent')->with('parent');
}

0 个答案:

没有答案