Laravel基于评级的碳趋势

时间:2015-08-03 17:37:33

标签: php laravel laravel-5

我想根据传入的时间段了解某个产品是否在我的网站上趋势(趋势向上或向下)。如果传入星期,它会将当前周与当天相比较,直到同一天为止。 例如如果今天是星期三,并且该模式是一周,它将比较本周至今,上周至上周三。

我到目前为止:

public function getTrendAttribute($period)
{
    $last_period = $this->ratings()->where(DB::raw(), )->avg('rating');
    $this_period = $this->ratings()->where(DB::raw(), )->avg('rating');
}

我不认为这是正确的开始:(。

我如何实现这一目标(我的应用程序中有Carbon库)?

这个怎么样?我不确定它是否非常有效,但似乎给了我一些有意义的数字:

public function getTrendAttribute($period)
{
    $tz = 'Europe/London';
    $this_week_start = Carbon::now($tz)->startOfWeek();
    $now = Carbon::now($tz);

    $last_week_start = Carbon::now($tz)->subWeek(1)->startOfWeek();
    $now_last_week = Carbon::now($tz)->subWeek(1);

    $last_period = $this->ratings()->where('created_at', '>=', $last_week_start)->where('created_at', '<=', $now_last_week)->avg('rating');
    $this_period = $this->ratings()->where('created_at', '>=', $this_week_start)->where('created_at', '<=', $now)->avg('rating');

    return $last_period > $this_period ? -1 : $last_period < $this_period ? 1 : 0;
}

1 个答案:

答案 0 :(得分:2)

试试这个。请注意,它特定于周分组,您必须按月,日或其他类似方式修改该查询以进行分组。但是你应该能够使用MySQL日期函数来实现这一目标。

$last_period = $this->ratings()->where(DB::raw('week(created_at)'), DB::raw('week(now()) - 1'))->where(DB::raw('dayofweek(created_at)'), '<=', DB::raw('dayofweek(now())'))->avg('rating');
$this_period = $this->ratings()->where(DB::raw('week(created_at)'), DB::raw('week(now())')->avg('rating');