ajax - 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();
我在搜索结果中两次获得每种产品。不知道为什么。这张图片给出了一个示例响应。
谁能帮我优化我的查询以获得所需的结果?
解决方案
仅在必要时才加入类别表。
并严格选择您的列。然后按选定的列分组。
$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();
推荐阅读
- reactjs - 是的,使用 Formik,Material-UI - React 的表单数组和嵌套表单组的模式生成器
- django - Django-Cookie-Consent 演练或教程
- python - 为什么我的 pyhhont 网络服务器不起作用?
- python-3.x - 将 blob 对象下载为字符串,而不是将其保存为文件然后读取它
- angular - Angular - 被 CORS 策略阻止:“Access-Control-Allow-Origin”标头包含多个值“*、*”
- javascript - 使用按钮创建新组件
- simulation - 为大公司建模的基于代理的模拟?
- regex - 怎么说,在小组赛中,“除非只有空格”?
- c# - 使用静态方法和静态类读写json文件好不好?
- instagram-graph-api - 如何在使用 axios 访问 instagram api 时解决状态码 429