在数据库Laravel 4的两个日期之间雄辩

时间:2018-04-23 12:08:29

标签: laravel laravel-4 eloquent

我在数据库中有优惠券或优惠券表。有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();
}

3 个答案:

答案 0 :(得分:1)

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();
}

试试这个

答案 1 :(得分:0)

你正在使用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()方法将条件作为字符串。

答案 2 :(得分:0)

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'];