【问题标题】:Eloquent between two dates from database, Laravel 4数据库中两个日期之间的雄辩,Laravel 4
【发布时间】:2018-10-03 11:28:56
【问题描述】:

我在数据库中有一张优惠券或优惠券表。有 start_date 和 finish_date 来确定凭证或优惠券的有效性。通过获取当天的日期、日期和时间,如果有效期仍然有效,则可以使用优惠券或优惠券,如果有效期已过,则无法重复使用优惠券或优惠券。 下面是我用来处理代金券或优惠券的源代码,但效果不是很好。 有没有人可以帮助我解决这个问题? 谢谢

public function coupon()
{
    $c = Input::get('coupon');
    $date = Carbon::now();
    $check = StoreVoucher::whereRaw("code = '".$c."'")
    ->whereRaw("status = 1")
    ->whereRaw("start_date", ">=", $date)
    ->whereRaw("finish_date", "<=", $date)
    ->first();
}

【问题讨论】:

  • 你遇到了什么错误?
  • 你为什么用whereRaw()而不是where()whereRaw("code = '".$c."'") 非常不安全,因为它容易受到 SQL 注入的攻击。
  • @MuhammadRizwan 没什么错误,只是我的加载过程需要很长时间
  • 如果你的网站速度太慢,这个简单的查询肯定不是原因。
  • 你迁移的 start_date 和 finsh_date 的数据类型是什么?

标签: laravel laravel-4 eloquent


【解决方案1】:
public function coupon() {    
    return StoreVoucher::where('code', Input::get('coupon'))
                         ->where('status', '1')
                         ->where('start_date', '>=', Carbon::now())
                         ->where('finish_date', '<=', Carbon::now())
                         ->first();
}

将此添加到您的 StoreVoucher 模型中:

protected $dates = ['start_date', 'finish_date'];

【讨论】:

  • 感谢您提供的答案,但是代码仍然是错误的,没有错误消息只是单击按钮需要很长时间时加载的过程
  • 我添加了受保护的 $dates = ["start_date", "finish_date", "deleted_at"];但错误出现 Class 'Carbon' not found
  • 你能添加2个字段的列结构吗,创建迁移时的代码行会做例如$table-&gt;dateTime('start_date') 以及数据库中的示例记录
  • @AgusSuparman 也在顶部命名空间声明后添加use Carbon\Carbon;
【解决方案2】:

您正在使用 whereRaw,但使用方式错误。

public function coupon()
{
    $c = Input::get('coupon');
    $date = Carbon::now();
    $check = StoreVoucher::whereRaw("code = '".$c."'")
    ->whereRaw("status = 1")
    ->whereRaw("start_date >= '$date'")
    ->whereRaw("finish_date <= '$date'")
    ->first()
}

WhereRaw() 方法将条件作为字符串。

【讨论】:

  • 感谢您提供的答案,但是代码仍然是错误的,没有错误消息只是单击按钮需要很长时间时加载的过程
  • 我添加了受保护的 $dates = ["start_date", "finish_date", "deleted_at"];但错误出现 Class 'Carbon' not found
【解决方案3】:
public function coupon()
{
    $c = Input::get('coupon');
    $date = Carbon::now();
    $check = StoreVoucher::where("code",$c)
    ->whereStatus(1)
    ->whereDate("start_date", ">=", $date)
    ->whereDate("finish_date", "<=", $date)
    ->first();
}

试试这个

【讨论】:

  • 尝试格式化日期$date-&gt;format('Y-m-d')作为保存在数据库中的方式
猜你喜欢
  • 1970-01-01
  • 2018-07-24
  • 1970-01-01
  • 1970-01-01
  • 2013-12-12
  • 2020-01-13
  • 1970-01-01
  • 2019-07-01
  • 1970-01-01
相关资源
最近更新 更多