首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >orderByRaw产品价格( discount_price,discount_price),未定义价格

orderByRaw产品价格( discount_price,discount_price),未定义价格
EN

Stack Overflow用户
提问于 2020-07-30 04:05:26
回答 1查看 108关注 0票数 0
代码语言:javascript
运行
复制
    Product => id, name, price  
    Discount => id, percent, date_start, date_end  
    discount_products (Table) => product_id, discount_id 
    
    Product::addSelect(['discount_price' => function ($query) {
        $query->selectRaw('SUM(products.price * (100 - discounts.percent) / 100)')
            ->from('discounts')
            ->join('discount_products', 'discounts.id', '=', 'discount_products.discount_id')
            ->whereColumn('discount_products.product_id', 'products.id')
            ->where('date_start', '<=', Carbon::today()->toDateString())
            ->where('date_end', '>=', Carbon::today()->toDateString())
            ->groupBy('id')
            ->orderBy('id', 'desc')
            ->limit(1);
        }])
    //  ->orderByRaw('COALESCE(discount_price, price) ASC')     // not working
    //  ->orderByRaw('discount_price ASC')                      // working
    //  ->orderByRaw('price ASC')                               // working
        ->get();

朋友们,大家好,首先为我的英语道歉。我使用PostgreSQL作为我的数据库。

我想按价格订购产品。

如果产品有“价格”,请使用它或使用“discount_price”字段。请帮帮忙。

EN

回答 1

Stack Overflow用户

发布于 2020-07-30 05:09:07

代码语言:javascript
运行
复制
Product::fromSub(function ($query) {
    $query->from("products")
        ->addSelect(['discount_price' => function ($query) {
            $query->selectRaw('SUM(products.price * (100 - discounts.percent) / 100)')
                ->from('discounts')
                ->join('discount_products', 'discounts.id', '=', 'discount_products.discount_id')
                ->whereColumn('discount_products.product_id', 'products.id')
                ->where('date_start', '<=', Carbon::today()->toDateString())
                ->where('date_end', '>=', Carbon::today()->toDateString())
                ->groupBy('id')
                ->orderBy('id', 'desc')
                ->limit(1);
        }]);
    }, 't')
    ->orderByRaw('COALESCE(discount_price, price) ASC')
    ->get();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63161632

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档