I have two SQL tables with columns:
menu:
- id [AI]
- name
- description
subcategories:
- id [AI]
- name
- pid (subcategory parent id)
- mid (menu id)
In the new version of my website there is no menu anymore and "subcategories" are now changed into "categories":
- id
- name
- description
- parent_id
The old database is still in use, so I'm making my migration script and here is the part with categories:
$new_db->query("TRUNCATE TABLE `categories`");
$ids = [];
$menu_list = $old_db->fetch("SELECT * FROM `menu` ORDER BY `id`");
foreach($menu_list as $menu)
{
$id = $new_db->insert("categories", [
"name" => $menu["name"],
"description" => $menu["description"],
"parent_id" => "0"
]);
$ids[$menu["id"]] = $id;
}
$subcategories = $old_db->fetch("SELECT * FROM `subcategories` ORDER BY `id`");
foreach($subcategories as $subcategory)
{
$pid = 0;
$desc = "";
if($subcategory["mid"] > 0)
{
$menu = $old_db->fetch_first("SELECT `id`, `description` FROM `menu` WHERE `id` = '".$subcategory["mid"]."' LIMIT 1");
$pid = $ids[$menu["id"]];
$desc = $menu["description"];
}
else
{
$pid = $subcategory["pid"];
}
$new_db->insert("categories", [
"name" => $subcategory["name"],
"description" => $desc,
"parent_id" => $pid
]);
}
It works but I'm pretty sure it could be done better with lesser cost. Can I make a SQL statement which will bind menu and subcategories into one result list and then insert them all?