I have 2 tables called categories and products with this relationship:
categories.category_id = products.product_category_id
I want to show all categories with 2 products of them!
[
[category 1] =>
[
'category_id' => 1,
'category_title' => 'category_title 1',
[products] => [
'0' => [
'product_category_id' => 1,
'product_id' => 51,
'product_title' => 'product_title 1',
],
'1' => [
'product_category_id' => 1,
'product_id' => 55,
'product_title' => 'product_title 2',
]
]
],
[category 2] =>
[
'category_id' => 2,
'category_title' => 'category_title 2',
[products] => [
'0' => [
'product_category_id' => 2,
'product_id' => 32,
'product_title' => 'product_title 3',
],
'1' => [
'product_category_id' => 2,
'product_id' => 33,
'product_title' => 'product_title 4',
]
]
],
...
]
I Laravel eloquent I can use something like this:
$categories = Category::with(['products' => function($q) {
$q->limit(2)
}])->get();
But I am not using Laravel and I need pure SQL code! I've tried this code:
SELECT
CT.category_id,
PT.product_category_id,
CT.category_title,
PT.product_id,
PT.product_title
FROM
categories CT
LEFT JOIN(
SELECT
*
FROM
products
LIMIT 2
) AS PT
ON
CT.category_id = PT.product_category_id
WHERE
CT.category_lang = 'en'
But there is a problem with this code! It seems that MYSQL first gets 2 first rows in products table and then tries to have a LEFT JOIN from categories to that 2 rows! and this cause returning null values for products (while if I remove LIMIT it works great but I need LIMIT)
I've tested this code too: (UPDATED)
SELECT
CT.category_id,
PT.product_category_id,
CT.category_title,
PT.product_id,
PT.product_title
FROM
categories CT
LEFT JOIN(
SELECT
*
FROM
products
WHERE
product_category_id = CT.category_id
LIMIT 5
) AS PT
ON
CT.category_id = PT.product_category_id
WHERE
CT.category_lang = 'en'
But I've received this error:
1054 - Unknown column 'CT.category_id' in 'where clause'
I cant access to CT.category_id in the subquery.
what is the best solution?