I need to combine 2 queries into a single join but my SQL skills are not the best.
Here's my query:
$query = $this->db->query("
SELECT p2c.product_id, p.model
FROM {$this->prefix}product_to_category p2c
LEFT JOIN {$this->prefix}product p
ON (p2c.product_id = p.product_id)
WHERE p.status < '3'
ORDER BY p2c.product_id ASC
");
$products = array();
foreach($query->rows as $product):
$cats = $this->db->query("
SELECT category_id
FROM {$this->prefix}product_to_category
WHERE product_id = '" . (int)$product['product_id'] . "'
");
$categories = array();
foreach($cats->rows as $category):
$categories[] = $category['category_id'];
endforeach;
$products[$product['model']] = array(
'product_id' => $product['product_id'],
'categories' => $categories
);
endforeach;
return $products;
The array I need returned needs to look like this:
[6596-27] => Array
(
[product_id] => 243
[categories] => Array
(
[0] => 7
[1] => 88
)
)
Obviously with this array being returned for each product in a larger single array.
I'm sure that this can be combined into a single query since the second query comes from one of the first queried tables but I can't understand how to grab all the categories into their own separate array without executing a second query.