drg14799 2015-08-03 17:37
浏览 26

Laravel基于评级的碳趋势

I want to find out if a product is trending on my website (trending up or down) based on the period that is passed in. I.e. If week is passed in, it compares the current week up to the day to the previous week up to the same day. e.g. If today is Wednesday, and the mode is week, it will compare this week up to today, with last week up to last Wednesday.

I have so far:

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

Which I don't think is the correct start :(.

How can I achieve this (I have the Carbon library in my app)?


What about this? I am not sure if it is very efficient but it seems to be giving me some numbers that make sense:

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条回答 默认 最新

  • douyi7055 2015-08-03 21:11
    关注

    Try this. Note that it is specific to the week grouping, and you would have to modify that query for grouping by month, or day, or anything else like that. But you should be able to use MySQL date functions to accomplish this.

    $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');
    
    评论

报告相同问题?

悬赏问题

  • ¥15 slam rangenet++配置
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊