I have a tree structured table, one of my table is Categories:
category_id | parent_id (in foreign key it is category_id) | title
And now I want to have a query and give it a category_id and it search whole table and go inside each children and get their children to the end point and select all.
I can do this by PHP, but I want to see how can I do it by SQL, this is my PHP code:
function getChild($id){
static $category_ids = [];
$category_ids[] = $id;
$list=$this->_model->select('categories','*', 'category_parent_id = '.$id);
foreach($list as $category) {
$category_ids[] = $category['category_id'];
if($category['last_child'] == 0){
$this->getChild($category['category_id']);
}
}
$category_ids = array_unique($category_ids);
return $category_ids;
}
//$list=$this->_model->select('categories','*', 'parent_id = '.$id);
//The above code is one of my functions (methods) and it select from table category * by parent_id
How to write a SQL query for it?
Which one is faster (PHP or that SQL query)