(Laravel 웅변은) 카테고리의 게시물과 모든 중첩 된 하위 범주를 가져옵니다

군중 :

내가 선택한 카테고리의 모든 게시물과 모든 중첩 된 하위 범주를 검색하고 싶습니다. 이 같은 I 평균 STH :

[id= 1]-Category 1
[id= 7]--Category 1.1
[id=12]---Category 1.1.1
[id=13]---Category 1.1.2
[id= 9]--Category 1.2
[id= 3]-Category 2

첫번째 I에서 반복적으로 선택 모든 카테고리의 ID와 중첩 된 모든 하위 범주를 얻을 다음 해당 카테고리 ID로 게시물을 검색하기 위해 노력했다.

나는 방법을 썼다 getSubcategoriesIds($category)내가 원하는하지만 중복 ID를 가진 배열을 반환 무엇을 실제로 줘 컨트롤러를. instans를 들어, 카테고리 (1) 내가 얻을 :

array:10 [
    0 => 1
    1 => 7
    2 => 1
    3 => 7
    4 => 12
    5 => 1
    6 => 7
    7 => 12
    8 => 13
    9 => 9
]

어떻게 중복없이 ID를 반환하는 방법을 향상시킬 수 있습니까? 아니면 그 게시물을 회복하기 위해 더 나은 방법은 무엇입니까?

여기 내 파일은 다음과 같습니다

모델 Category.php :

class Category extends Model {

    public function parent() {
        return $this->belongsTo('App\Category', 'parent_id');
    }

    public function children() {
        return $this->hasMany('App\Category', 'parent_id');
    }

    public function subcategories() {
        return $this->children()->with('subcategories');
    }

    public function parents() {
        return $this->parent()->with('parents');
    }

    public function posts(){
        return $this->hasMany('App\Post');
    }
}

PostController.php :

public function show($id)
{
    $ids =$this->getSubcategoriesIds(Category::with('subcategories')->where('id', $id)->first()));
    $posts = Post::whereIn('category_id', $ids)->get();
    return view('post.index', compact('posts'));
}

public function getSubcategoriesIds($category) {
    $array = [$category->id];
    if(count($category->subcategories) == 0) {
        return $array;
    } 
    else  {
        foreach ($category->subcategories as $subcategory) {
            array_push($array, $subcategory->id);
            if(count($subcategory->subcategories)){
                $array = array_merge($array, $this->getChildren($subcategory->subcategories, $array));
            }
        }
        return $array;
    }
}

public function getChildren($subcategories, $array) {
    foreach ($subcategories as $subcategory)  {
        array_push($array, $subcategory->id);
        if(count($subcategory->subcategories)){
            return $array = array_merge($array, $this->getChildren($subcategory->subcategories, $array));
        }
        return $array;
    }
}
군중 :

내 재귀 방법으로 문제를 발견했다. 나는 통과하지 않아야 $array재귀 방법 getChildrenIds().

여기에 (일부 리팩토링과) 내 솔루션입니다 :

    public function getCategoriesIds($category)
{
    if(!empty($category))
    {
        $array = array($category->id);
        if(count($category->subcategories) == 0) return $array;
        else return array_merge($array, $this->getChildrenIds($category->subcategories));
    } 
    else return null;
}

public function getChildrenIds($subcategories)
{
    $array = array();
    foreach ($subcategories as $subcategory)
    {
        array_push($array, $subcategory->id);
        if(count($subcategory->subcategories))
            $array = array_merge($array, $this->getChildrenIds($subcategory->subcategories));
    }
    return $array;
}

지금 $this->getCategoriesIds(Category::with('subcategories')->where('id', 1)->first());반환

array:10 [
0 => 1
1 => 7
2 => 12
3 => 13
4 => 9
]

추천

출처http://43.154.161.224:23101/article/api/json?id=8913&siteId=1