猿问

基于过期状态的 OrderBy 优惠券 Laravel

我需要显示优惠券列表并根据 created_at 日期和到期状态对其进行排序。


我的优惠券表的列


id

name

price

expired_at

created_at

status

我的 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 (最新和正在进行的优惠券在顶部名单)


所以可能需要创建临时列来获取过期状态,然后才能对列表进行排序。任何想法如何实现这一目标?


慕哥6287543
浏览 171回答 3
3回答

www说

比较过期日期和今天 ( expired_at < NOW())$coupons= Coupon::where('status', 2)->orderByRaw(&nbsp;"CASE WHEN expired_at IS NULL OR expired_at > CURDATE() THEN 1 ELSE 0 END DESC");

长风秋雁

你也可以这样写:$coupons=&nbsp;Coupon::where('status',&nbsp;2)->orderBy([&nbsp;'coupon_status'&nbsp;=>&nbsp;'ASC',&nbsp;'created_at'&nbsp;=>&nbsp;'DESC'&nbsp;])->get();我希望它会帮助你:)

蝴蝶不菲

只需使用ORDER BY coupon_status ASC, created_at DESC'这expired_at可以与CURDATE():试试这个查询:$coupons=&nbsp;Coupon::where('status',&nbsp;2) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;->orderBy(\DB::raw('(IF((expired_at&nbsp;IS&nbsp;NULL&nbsp;OR&nbsp;expired_at&nbsp;<&nbsp;CURDATE()),&nbsp;1,&nbsp;0&nbsp;))&nbsp;ASC,&nbsp;created_at&nbsp;DESC')) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;->get();
随时随地看视频慕课网APP
我要回答