laravel 产品 orderByRaw COALESCE(discount_price, price), discount_price 未定义
Posted
技术标签:
【中文标题】laravel 产品 orderByRaw COALESCE(discount_price, price), discount_price 未定义【英文标题】:laravel products orderByRaw COALESCE(discount_price, price), discount_price not defined 【发布时间】: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' 字段。请帮忙。
【问题讨论】:
如果您能解释您需要的查询,那就太好了。 我想按价格订购产品。但有些产品有折扣 请创建示例数据,然后以您需要的确切格式显示输出。在帖子中添加所有这些内容。 【参考方案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();
【讨论】:
以上是关于laravel 产品 orderByRaw COALESCE(discount_price, price), discount_price 未定义的主要内容,如果未能解决你的问题,请参考以下文章
ORMLite QueryBuilder.orderByRaw(String, SelectArg) 忽略 QueryBuilder.queryRaw() 上的 SelectArg