【问题标题】:OrderBy Coupons based on expiration status Laravel基于过期状态的 OrderBy 优惠券 Laravel
【发布时间】:2020-04-19 20:13:15
【问题描述】:

我需要显示优惠券列表并根据 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 created_at(最新和正在进行的优惠券在列表的顶部)

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

【问题讨论】:

  • 如果您对查询有任何疑问,请尝试 ->toSql() 而不是 ->get()
  • 什么是coupon_status?你在存储expired_at吗?
  • coupon_status 不是列数据库,它只是根据今天的日期,如果优惠券已经过期或不是状态,expired_at 是优惠券的过期日期

标签: php mysql laravel laravel-5 eloquent


【解决方案1】:

比较过期日期和今天 (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"
);

【讨论】:

  • 我编辑了问题,优惠券状态需要先与今天的日期进行比较,它不在数据库列上
  • 查询正常但订购列表不正确,部分过期优惠券仍显示在正在进行的优惠券上方 ->orderBy('created_at', 'DESC')->orderByRaw("CASE WHEN expired_atoDateString()." THEN 0 WHEN expired_a IS NULL THEN 1 ELSE 1 END DESC")
  • @TomKur 已更新,如果您使用日期数据类型,则必须使用 CURDATE() 而不是 Now()
  • 它的工作,我不知道我不能使用碳日期,需要使用 CURDATE()
【解决方案2】:

只需使用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();

【讨论】:

  • 我编辑了问题,需要先将优惠券状态与今天的日期进行比较,它不在 db 列上
  • 我使用的查询 CASE WHEN ->orderByRaw("CASE WHEN expired_atoDateString()." THEN 0 WHEN expired_a IS NULL THEN 1 ELSE 1 END DESC, created_at DESC") -- 列表顺序不正确,一些过期的优惠券仍然显示在正在进行的优惠券上方
  • @TomKur is your expired_at is datetime or date?
  • expired_at 只是日期,NULL 表示没有过期日期,它将是持续的优惠券
【解决方案3】:

你也可以这样写:

$coupons= Coupon::where('status', 2)->orderBy([ 'coupon_status' => 'ASC', 'created_at' => 'DESC' ])->get();

希望对你有帮助:)

【讨论】:

  • 我编辑了问题,优惠券状态需要先与今天的日期进行比较,它不在数据库列上
  • $coupons= Coupon::whereDate('expired_at', Carbon::today())->where('status', 2)->orderBy('created_at', 'DESC')- >get();请试试这个?希望对你有帮助
猜你喜欢
  • 2022-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-10
相关资源
最近更新 更多