Is it possible to reduce the number of joins when accessing the pivot table? #397
-
Hello. final class ApplyProductFilters
{
public function __invoke(Select $select, array $filters): Select
{
return $select->where(static function(Select\QueryBuilder $q) use ($filters) {
foreach ($filters as $filterID => $filterValue) {
$q->orWhere(static function(Select\QueryBuilder $q) use ($filterID, $filterValue) {
$q->where('[email protected]', $filterID);
if (is_array($filterValue)) {
$q->andWhere(static function(Select\QueryBuilder $q) use ($filterValue) {
if (count($filterValue) == 2 && is_numeric($filterValue[0]) && is_numeric($filterValue[1])) {
$q->orWhere('[email protected]', 'between', $filterValue[0], $filterValue[1]);
} else {
foreach ($filterValue as $value) $q->orWhere('[email protected]', $value);
}
});
} else {
$q->andWhere('[email protected]', $filterValue);
}
});
}
});
}
}
SELECT `product`.`id` AS `c0`, `product`.`name` AS `c1`, `product`.`price` AS `c2`, `product`.`attributes` AS `c3`, `product`.`description` AS `c4`, `product`.`created_at` AS `c5`,
`product`.`category_id` AS `c6`, `product`.`brand_id` AS `c7`
FROM `products` AS `product`
INNER JOIN `filters_products` AS `product_filters_pivot`
ON `product_filters_pivot`.`product_id` = `product`.`id`
INNER JOIN `filters` AS `product_filters`
ON `product_filters`.`id` = `product_filters_pivot`.`filter_id`
WHERE ((`product_filters_pivot`.`filter_id` = ? AND (`product_filters_pivot`.`filter_value` = ? OR `product_filters_pivot`.`filter_value` = ? ) )OR (`product_filters_pivot`.`filter_id` = ? AND (`product_filters_pivot`.`filter_value` BETWEEN ? AND ? ) ) )
LIMIT ? OFFSET ? I tried calling the join directly from the dd($select->innerJoin('filters_products', 'fp')->on('id', 'fp.product_id')->sqlStatement()); SELECT `product`.`id` AS `c0`, `product`.`name` AS `c1`, `product`.`price` AS `c2`, `product`.`attributes` AS `c3`, `product`.`description` AS `c4`, `product`.`created_at` AS `c5`,
`product`.`category_id` AS `c6`, `product`.`brand_id` AS `c7`
FROM `products` AS `product`
INNER JOIN `product`.`filters_products` AS `fp`
ON `product`.`id` = `fp`.`product_id`
LIMIT ? OFFSET ? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
You can make yet another relation like
Looks like a bug. I need to play with that |
Beta Was this translation helpful? Give feedback.
You can make yet another relation like
product
HasManyproduct_filters_pivot
and use it directly.BTW your question looks like a good issue for the
ManyToMany
relation.Looks like a bug. I need to play with that