laravel模型中的日期计算

时间:2019-01-07 13:46:59

标签: laravel

我想基于日期返回模型中的值,但不确定如何做?

逻辑

计算帖子发布的日期及其后的7天,然后返回true或false。

示例

假设我要从发布日期起至发布后7天,以及在new label被删除的第8天开始,在发布中添加new label

我该怎么做?

更新

我目前在模型中得到了类似的结果

public function isNew($query){
        return $query->where('created_at', '<=', Carbon::now()->toDateTimeString());
    }

但是它会在我的刀片中返回Undefined variable: isNew

请给我您的建议。

3 个答案:

答案 0 :(得分:0)

I would recommend you make use of Carbon:

https://carbon.nesbot.com/docs/#api-difference

That link should help a lot but to point you in the correct direction, you should be able to do a comparison:

I assume you DB date is held in ISO (Y-M-D, eg: 2019-01-07)

$date= Carbon::createFromFormat('Y-m-d', $dateFromDB);
if($date->diffInDays(Carbon::now() < 8){
    Code for Add Label here
}

Or if you are using timestamps:

$date= Carbon::createFromTimestamp($dateFromDB);
if($date->diffInDays(Carbon::now() < 8){
    Code for Add Label here
}

答案 1 :(得分:0)

Are labels stored in a separate table from your posts? You could use 'effective dating'. Have indexed 'show_at' and 'hide_at' fields in your labels table. Have entries there get created as soon as the post does. You could use database triggers to do this, or model observers. And when querying for all labels related to a given post, make sure they're between those dates (or those dates are null).

For a more simple solution, you could do a whereRaw('CURRENT_DATE <= DATE_ADD(dateFieldName, INTERVAL 7 DAY)'). If timezones are a factor, you could use the CONVERT_TZ() function, though it's generally good practice to store everything in UTC to avoid those issues.

答案 2 :(得分:0)

已解决

感谢我通过以下代码解决了我的问题的所有帮助:

 public function getisNewAttribute(){
        $now = Carbon::now();
        return Carbon::parse($now) <= Carbon::parse($this->created_at)->addDays(7);
    }
相关问题