首页 > 解决方案 > Laravel 查询生成器的产品过滤问题

问题描述

我尝试在我的电子商务项目主页中实现基于 ajax 的过滤来搜索产品。我正在使用 Laravel 查询生成器。我的过滤产品查询如下 -

 $result= DB::table('products')
    ->leftjoin('products_description','products.products_id','products_description.products_id')
    ->leftjoin('image_categories', 'products.products_image', '=', 'image_categories.image_id')
    ->leftjoin('products_to_categories','products.products_id','products_to_categories.products_id')
    ->leftjoin('categories','products_to_categories.categories_id','categories.categories_id')
    ->when($category_slug, function($q) use ($category_slug) {
        return $q->where('categories.categories_slug', $category_slug);
    })
    ->where('products_name','like',"%{$querval}%")
    ->where('image_categories.image_type','=','ACTUAL')
    ->orderby('products.products_id','DESC')
    ->take(5)
    ->get();

我在搜索结果中两次获得每种产品。不知道为什么。这张图片给出了一个示例响应。 回复

谁能帮我优化我的查询以获得所需的结果?

标签: ajaxlaravel

解决方案


仅在必要时才加入类别表。

并严格选择您的列。然后按选定的列分组。

 $result= DB::table('products')
            ->leftjoin('products_description','products.products_id','products_description.products_id')
            ->leftjoin('image_categories', 'products.products_image', '=', 'image_categories.image_id')
            ->when($category_slug, function($q) use ($category_slug) {
                return $q->leftjoin('products_to_categories','products.products_id','products_to_categories.products_id')
                    ->leftjoin('categories','products_to_categories.categories_id','categories.categories_id')
                    ->where('categories.categories_slug', $category_slug);
            })
            ->where('products_name','like',"%{$querval}%")
            ->where('image_categories.image_type','=','ACTUAL')
            ->orderby('products.products_id','DESC')
            ->select(['products_name','products.id','image_path'])
            ->groupBy(['products_name','products.id','image_path'])
            ->take(5)
            ->get();

推荐阅读