Consider the database table: folders
folders id parent_id name 1 0 a 2 1 b 3 2 c
‘b’ is a folder inside ‘a’ and thus it’s parent_id is the id of ‘a’.
Folders with a parent_id of 0 simply means it’s in the root folder.
I wrote a recursive function in php that helps me get the ID of a path that I’m interested in.
For example:
echo get_folder_id('a/b/c'); // 3 (3 SQL queries)
echo get_folder_id('a'); // 1 (1 SQL query)
echo get_folder_id('a/b'); // 2 (2 SQL queries)
echo get_folder_id('a/c'); // false (2 SQL queries)
Problem: For each folder in the path, I had to make a SQL query to the DB server.
Question: Is there a way I can reduce the number of queries if the path is ‘a/b/c’?
Here’s my current working solution for reference.
function get_folder_id($path, $parent_id=0) {
$path = explode('/', $path);
$id = 0;
//if there's only 1 folder in the path, query the database for the ID
if (count($path) == 1) {
$rs = $this->db->select('id')
->from('folders')
->where('name', $path[0])
->where('parent_id', $parent_id)
->limit(1)
->get();
if ($rs->num_rows() == 0) return FALSE;
$result = $rs->row_array();
return $result['id'];
}
foreach($path AS $i=>$p) {
if ($i==0 && $p=='') continue; //if a path starts with / move on to the next item
$id = $this->get_folder_id($p, $id);
}
return $id;
}
Note: I’m using CodeIgniter framework but this isn’t related to my question. Just for folks wondering why I used $this->get_folder_id() and $this->db
One solution I just came up is to use a series of LEFT JOINs on the same table.
Based on the number of folders in the path, I can dynamically generate the above SQL.
I’m not sure if this is the perfect solution, but right now it’s working as intended.
Any feedback on whether this is a good idea or not is greatly appreciated!