i have category table, and sub categories also in same table... if some category have null parent_id its top node category.
table basic fields like this:
---------------------
|id |name |parent_id|
---------------------
I just need to get all childs ids in minimum quarry execution:
eg:
Category::find(2)->allChildIds(); //result like [3,4,6,10,....]
i have this relationship added:
public function parent(){
return $this->belongsTo(Category::class);
}
public function childs(){
return $this->hasMany(Category::class,'parent_id');
}
thank you
My Answer:
You can achieve this by creating a recursive function in your Category model. Here's an example of how you can do this:
php
class Category extends Model
{
public function parent(){
return $this->belongsTo(Category::class);
}
public function childs(){
return $this->hasMany(Category::class,'parent_id');
}
public function allChildIds()
{
$childIds = [];
$this->getChildIds($this, $childIds);
return $childIds;
}
private function getChildIds($category, &$childIds)
{
foreach ($category->childs as $child) {
$childIds[] = $child->id;
$this->getChildIds($child, $childIds);
}
}
}
Now you can use the `allChildIds()` method to get all child ids of a specific category:
php
$childIds = Category::find(2)->allChildIds();
This will return an array of all child ids of the category with id 2.
Rate this post
3 of 5 based on 8899 votesComments