群衆:
私が選択したカテゴリのすべての記事およびすべてのネストされたサブカテゴリを取得したいと思います。このようなI平均かないました:
[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
最初に私には再帰的に選択したカテゴリのすべての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
]