用最粗糙的方法,写出了查询简单的商品筛选的 SQL 语句,请问我该如何简化,使他看起来更优雅??

laravel 版本 5.1

下面是我写的查询语句,可愁死我了,功能实现倒是实现了,写的太难受了,重复好多,请问我该如何简化呢,或者该怎么传入变量查询,或者有什么其他方法简化,请举例,或演示部分,谢谢

public function postTreat(Request $request)
{
    $_page = $request->input("_page"); //页码
    $_path = $request->input("_path"); //第三级 path
    $_sortType = $request->input("_sortType"); //综合类别

    $_sales = $request->input("_sales"); //销售优先
    $_priceSmall = $request->input("_priceSmall"); //最低价
    $_priceBig = $request->input("_priceBig"); //最高价

    $page=($_page-1)*4;

    /**
     * 构建出一个公共的 Query
     *
     * @var $shopGoodsQuery \Illuminate\Database\Query\Builder
     */
    $shopGoodsQuery = DB::table('shop_goods')
                            ->where('goods_cid',$_path)
                            ->where('goods_status',1) // 0未审核 1审核通过 2审核未通过
                            ->where('goods_state',0) // 0已上架 1已下架
                            ->where('goods_recycle',0); // 0正常 1回收站

    // 是否有价格区间限制
    if(empty($_priceSmall)&&empty($_priceBig)){
        // 是否按销量排序
        if(empty($_sales)){
            // 是否有综合排序 判断综合类别
            if($_sortType=="composite" || $_sortType==""){//综合 或 没有
                $data = $shopGoodsQuery->skip($page)->take(4)->get();
            }else if($_sortType=="price_up"){ //价格最低
                $data = $shopGoodsQuery
                            ->orderBy('goods_price','asc') // 价格最低
                            ->skip($page)
                            ->take(4)
                            ->get();
            }else if($_sortType=="price_down"){ //价格最高
                $data = $shopGoodsQuery
                            ->orderBy('goods_price','desc') // 价格最高 
                            ->skip($page)
                            ->take(4)
                            ->get();
            }else if($_sortType=="assess_down"){ // 评价最多
                // 只有在走这个区间的时候,才需要关联查询 评价的数量
                $data = DB::table('shop_goods')
                            ->leftJoin('shop_assess', 'shop_goods.goods_id', '=', 'shop_assess.assess_gcode')
                            ->selectRaw('shop_goods.*,COUNT(shop_assess.assess_id) as assess_num')
                            ->where('shop_goods.goods_cid',$_path)
                            ->where('shop_goods.goods_status',1) // 0未审核 1审核通过 2审核未通过
                            ->where('shop_goods.goods_state',0) // 0已上架 1已下架
                            ->where('shop_goods.goods_recycle',0) // 0正常 1回收站
                            ->groupBy('shop_goods.goods_id')
                            ->orderBy('assess_num','desc')
                            ->skip($page)
                            ->take(4)
                            ->get();
            }else if($_sortType=="publish_new"){ //最新发布
                $data = $shopGoodsQuery
                            ->orderBy('goods_time','desc') // 最新发布
                            ->skip($page)
                            ->take(4)
                            ->get();
            }
        }else{
            $data = $shopGoodsQuery
                        ->orderBy('goods_num','desc') // 销售倒序排列
                        ->skip($page)
                        ->take(4)
                        ->get();
        }
    }else{
        // 是否按销量排序
        if(empty($_sales)){
            // 是否有综合排序 判断综合类别
            if($_sortType=="composite" || $_sortType==""){
                $data = $shopGoodsQuery
                            ->whereBetween('goods_price',[$_priceSmall,$_priceBig]) // 价格区间
                            ->skip($page)
                            ->take(4)
                            ->get();
            }else if($_sortType=="price_up"){
                $data = $shopGoodsQuery
                            ->whereBetween('goods_price',[$_priceSmall,$_priceBig]) // 价格区间
                            ->orderBy('goods_price','asc') // 价格最低
                            ->skip($page)
                            ->take(4)
                            ->get();
            }else if($_sortType=="price_down"){
                $data = $shopGoodsQuery
                            ->whereBetween('goods_price',[$_priceSmall,$_priceBig]) // 价格区间
                            ->orderBy('goods_price','desc') // 价格最高 
                            ->skip($page)
                            ->take(4)
                            ->get();
            }else if($_sortType=="assess_down"){
                $data = DB::table('shop_goods')
                            ->leftJoin('shop_assess', 'shop_goods.goods_id', '=', 'shop_assess.assess_gcode')
                            ->selectRaw('shop_goods.*,COUNT(shop_assess.assess_id) as assess_num') //统计评价的数量
                            ->where('shop_goods.goods_cid',$_path)
                            ->where('shop_goods.goods_status',1) // 0未审核 1审核通过 2审核未通过
                            ->where('shop_goods.goods_state',0) // 0已上架 1已下架
                            ->where('shop_goods.goods_recycle',0) // 0正常 1回收站
                            ->whereBetween('shop_goods.goods_price',[$_priceSmall,$_priceBig]) // 价格区间
                            ->groupBy('shop_goods.goods_id')
                            ->orderBy('assess_num','desc')
                            ->skip($page)
                            ->take(4)
                            ->get();
            }else if($_sortType=="publish_new"){
                $data = $shopGoodsQuery
                            ->whereBetween('goods_price',[$_priceSmall,$_priceBig]) // 价格区间
                            ->orderBy('goods_time','desc') // 最新发布
                            ->skip($page)
                            ->take(4)
                            ->get();
            }
        }else{
            $data = $shopGoodsQuery
                        ->whereBetween('goods_price',[$_priceSmall,$_priceBig])
                        ->orderBy('goods_num','desc')
                        ->skip($page)
                        ->take(4)
                        ->get();
        }
    }

    foreach($data as $key => $value){
        if($value->goods_num>10000){
            $value->goods_num = round(($value->goods_num)/10000,1).'w';
        }
    }
    return $data;
}
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
最佳答案

写一段大概的代码,具体细节你需要再重写一下

     protected $orderByMap = [
        'assess_down' => ['assess_num', 'desc'],
        'price_up' => ['goods_price', 'asc'],
        'price_down' => ['goods_price', 'desc'],
        'publish_new' => ['goods_time', 'desc'],
    ];

    /**
     * @param Request $request
     * @return mixed
     */
    public function postTreat(Request $request)
    {
        // 页码
        $_page = $request->input("_page");
        $page = ($_page-1)*4;

        /**
         * 构建出一个公共的 Query
         *
         * @var $shopGoodsQuery \Illuminate\Database\Query\Builder
         */
        $shopGoodsQuery = DB::table('shop_goods')
                            ->where('goods_status', 1)// 0未审核 1审核通过 2审核未通过
                            ->where('goods_state', 0)// 0已上架 1已下架
                            ->where('goods_recycle', 0); // 0正常 1回收站;

        // 最低价
        $shopGoodsQuery->when($request->input('_priceSmall'), function (Builder $query, $priceSmall) {
            $query->where('goods_price', '>', $priceSmall);
        });

        // 最高价
        $shopGoodsQuery->when($request->input('_priceBig'), function (Builder $query, $priceBig) {
            $query->where('goods_price', '<', $priceBig);
        });

        // 是否按总和排序
        $shopGoodsQuery->when($request->input("_sales"), function (Builder $query, $sales) {
            $query->where('goods_num', 'desc');
        }, function (Builder $query, $sales) {
            // 不按总价排序的, 这个相当于 else

        });

        // 排序用 map 表映射找出字段排序
        $shopGoodsQuery->when($request->input("_sortType"), function (Builder $query, $sortType) {
            // 得到要排序的字段, 如果没有就按默认的第一种排序
            list($field, $orderBy) = $this->orderByMap[$sortType] ?? array_first($this->orderByMap);
            $query->orderBy($field, $orderBy);
        });

        // 最后进行统一分页
        $data = $shopGoodsQuery->skip($page)->take(4)->get();

        dd($data);
    }
5年前 评论
讨论数量: 2

写一段大概的代码,具体细节你需要再重写一下

     protected $orderByMap = [
        'assess_down' => ['assess_num', 'desc'],
        'price_up' => ['goods_price', 'asc'],
        'price_down' => ['goods_price', 'desc'],
        'publish_new' => ['goods_time', 'desc'],
    ];

    /**
     * @param Request $request
     * @return mixed
     */
    public function postTreat(Request $request)
    {
        // 页码
        $_page = $request->input("_page");
        $page = ($_page-1)*4;

        /**
         * 构建出一个公共的 Query
         *
         * @var $shopGoodsQuery \Illuminate\Database\Query\Builder
         */
        $shopGoodsQuery = DB::table('shop_goods')
                            ->where('goods_status', 1)// 0未审核 1审核通过 2审核未通过
                            ->where('goods_state', 0)// 0已上架 1已下架
                            ->where('goods_recycle', 0); // 0正常 1回收站;

        // 最低价
        $shopGoodsQuery->when($request->input('_priceSmall'), function (Builder $query, $priceSmall) {
            $query->where('goods_price', '>', $priceSmall);
        });

        // 最高价
        $shopGoodsQuery->when($request->input('_priceBig'), function (Builder $query, $priceBig) {
            $query->where('goods_price', '<', $priceBig);
        });

        // 是否按总和排序
        $shopGoodsQuery->when($request->input("_sales"), function (Builder $query, $sales) {
            $query->where('goods_num', 'desc');
        }, function (Builder $query, $sales) {
            // 不按总价排序的, 这个相当于 else

        });

        // 排序用 map 表映射找出字段排序
        $shopGoodsQuery->when($request->input("_sortType"), function (Builder $query, $sortType) {
            // 得到要排序的字段, 如果没有就按默认的第一种排序
            list($field, $orderBy) = $this->orderByMap[$sortType] ?? array_first($this->orderByMap);
            $query->orderBy($field, $orderBy);
        });

        // 最后进行统一分页
        $data = $shopGoodsQuery->skip($page)->take(4)->get();

        dd($data);
    }
5年前 评论

@DavidNineRoc 谢谢您的回答,实在不好意思,没有在问题中标明 laravel 的版本我用的是5.1 的,所有还没有when构成的条件查询语句 :pray:

5年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!