V
V
vadim072018-07-15 13:07:50
Laravel
vadim07, 2018-07-15 13:07:50

How to make a selection of goods with filtering by linked tables with a many-to-many relationship?

There is a table with goods goods. It is linked to the categories (many to many) table, as well as to the goods_filter_value (many to many) table. How to make a selection with a given category alias and an array of filters?
Now I do this:

protected function getProducts($alias, $filters = [])
    {
        $products = $this
            ->p_rep
            ->model
            ->select(
                'goods.name', 
                'goods.price',
                'goods.alias',
                'goods.discount_price',
                'goods.isNew', 
                'images.path'
                )
            ->join('images', 'goods.id', '=', 'images.product_id')
            ->join('goods_category', 'goods_category.product_id', '=', 'goods.id')
            ->join('categories', 'goods_category.category_id', '=', 'categories.id');

            if(count($filters) > 0 ){
                $products = $products->join('goods_filter_value', 'goods_filter_value.product_id', '=', 'goods.id')
                    ->join('values_filters', 'goods_filter_value.value_id', '=', 'values_filters.id')
                    ->whereIn('values_filters.id', $filters);
            }

            $products = $products->where('categories.alias', $alias)            
                ->where('images.isMain', 1)
                ->distinct()
                ->orderBy('goods.created_at', 'desc')
                ->paginate(\Config::get('settings.count_products_on_page'), ['goods.*']);

        return $products;
    }

the problem is that when I apply more filters, there are more results and not vice versa + there is a problem with total in pagination due to distinct

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
ApeCoder, 2018-07-15
@ApeCoder

... Where exists (select ...
www.sql-tutorial.ru/ru/book_exists_predicate.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question