【问题标题】:laravel products orderByRaw COALESCE(discount_price, price), discount_price not definedlaravel 产品 orderByRaw COALESCE(discount_price, price), discount_price 未定义
【发布时间】:2020-11-19 12:25:31
【问题描述】:
    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' 使用它或使用 'price' 字段。请帮忙。

【问题讨论】:

  • 如果您能解释您需要的查询,那就太好了。
  • 我想按价格订购产品。但有些产品有折扣
  • 请创建示例数据,然后以您需要的确切格式显示输出。在帖子中添加所有这些内容。

标签: laravel eloquent laravel-6 laravel-query-builder


【解决方案1】:
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();

【讨论】:

    猜你喜欢
    • 2021-10-28
    • 1970-01-01
    • 2019-05-10
    • 2020-09-20
    • 2021-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多