SELECT * FROM `products`
INNER JOIN `category_products` ON `category_products`.`product_id` = `products`.`id`
INNER JOIN `filter_options_products` ON `filter_options_products`.`product_id` = `products`.`id`
WHERE `category_products`.`category_id` = 2
AND `filter_option_id` IN (1,2,3)
SELECT products.*,
COALESCE((SELECT GROUP_CONCAT(fo.url_slug) FROM filters_options_item foi
JOIN filters_options fo ON fo.id = foi.filter_option_id
WHERE foi.product_id = products.id), '') AS filters
FROM products
JOIN categories_products cp ON cp.product_id = products.id
JOIN categories c ON c.id = cp.category_id
WHERE c.url_slug = ?
Code (PHP)
#@filters = all applicable filters for current category
# loop through @filters
# loop through filter options for this filter
# filter product results to include any selected filter options for this filter
# if there are no filter options selected for this filter, include all products
# build the url for each filter option, to toggle the filter option (on or off)
# loop through @filters (yes, a second time)
# loop through filter options for this filter
# count remaining products for each filter option, if none, set filter option to inactive
# build the final url for each filter option, based on all filters turned on and off
### --- vFilter ---- View in database
select ft.*, dt.ft_Type, dt.ref_op_or_cg, dt.ref_for_category_id,
from filters as ft
inner join (
select 'cg' as ft_Type, fc.category_id as ref_op_or_cg, fc.filter_id as ft_ID, fc.id ref_for_category_id, cp.product_id
from filters_categories fc left join category_product cp on cp.category_id = fc.category_id
union all
select 'op' as ft_Type, id, filter_id, null, fop.product_id
from filter_options as fo left join filter_options_product fop on fop.fileter_option_id = fo.id
) as dt on dt.ft_ID = ft.id
Code (PHP)
$sql="select pd.* from products pd
left join vFilter v
on v.id = $request_filter_select_id ## อ้างอิงตาราง filters
and (
(
v.ft_Type = 'cg'
and
v.ft_ID in (".implode(',', $request_filter_category).")) ## อ้างอิง category
or
(
v.ft_Type = 'op'
and
v.ft_ID in (".implode(',', $request_filter_option).")) ## อ้างอิง option
)
and pd.id = v.product_id
group by pd.id having count(ft.*)=".(count($request_filter_category)+count($request_filter_option);