我需要顯示優惠券列表并根據 created_at 日期和到期狀態對其進行排序。我的優惠券表的列idnamepriceexpired_atcreated_atstatus我的 laravel 查詢$coupons= Coupon::where('status', 2)->orderBy('created_at', 'DESC')->orderBy( First I will need to compare expired_at with today date here)->get();問題是我不知道如何 orderBy coupon_status,我想在列表底部顯示所有過期的優惠券,在列表頂部顯示正在進行的優惠券,并且 orderBy created_at (最新和正在進行的優惠券在頂部名單)所以可能需要創建臨時列來獲取過期狀態,然后才能對列表進行排序。任何想法如何實現這一目標?
3 回答

www說
TA貢獻1775條經驗 獲得超8個贊
比較過期日期和今天 ( expired_at < NOW())
$coupons= Coupon::where('status', 2)->orderByRaw(
"CASE WHEN expired_at IS NULL OR expired_at > CURDATE() THEN 1 ELSE 0 END DESC"
);

長風秋雁
TA貢獻1757條經驗 獲得超7個贊
你也可以這樣寫:
$coupons= Coupon::where('status', 2)->orderBy([ 'coupon_status' => 'ASC', 'created_at' => 'DESC' ])->get();
我希望它會幫助你:)

蝴蝶不菲
TA貢獻1810條經驗 獲得超4個贊
只需使用ORDER BY coupon_status ASC, created_at DESC'
這expired_at
可以與CURDATE()
:
試試這個查詢:
$coupons= Coupon::where('status', 2) ->orderBy(\DB::raw('(IF((expired_at IS NULL OR expired_at < CURDATE()), 1, 0 )) ASC, created_at DESC')) ->get();
- 3 回答
- 0 關注
- 148 瀏覽
添加回答
舉報
0/150
提交
取消