In my project I have the essence of the article . Each article may belong to several sections. This is easily accomplished by the many-to-many approach.
Articles id | name Categories id | name Article_categories id | article_id | category_id But I need to add subsections to the essentials, given that the article may belong to several subsections. In a simple view, this could be implemented with two additional tables.
Subcategories id | name Article_subcategoires id | article_id | subcategories_id And now the question. I need to get the data in a "hierarchical" way:
- get all articles
- get all articles / specific category / all subcategories
- get all articles / specific category / specific subcategory
- get all articles / all categories / specific subcategories
and here my knowledge and practice are no longer lacking, and the dual approach of many-to-many does not work, or rather, the result has been obtained, but is not sure of its correctness and effectiveness in terms of resources.
Bike on laravel 5.3
ArticleController.php $articles = Article::Published() ->ByCategory($cat) ->BySubcategory($subcat) ->paginate(10); Article.php Model public function scopeByCategory($query, $catRequest){ if($catRequest && $catRequest != 'all' ) { return $query->with('categories') ->whereHas('categories', function ($q) use ($catRequest) { $q->where('id', $catRequest); }); }else{ return $query; } } public function scopeBySubcategory($query, $subcatRequest){ if($subcatRequest && $subcatRequest != 'all' ) { return $query->with('subcategories') ->whereHas('subcategories', function ($q) use ($subcatRequest) { $q->where('id', $subcatRequest); }); }else{ return $query; } } But I have a persistent feeling that this is not right, and this is a bicycle. Are there any other solutions at the level of database design or data processing in php?