dongpigui8898 2017-01-26 23:59
浏览 54
已采纳

将用户的时区应用于Laravel中的模型属性

In Laravel 5.3, I've written a collection designed to cycle through a user's bills and determine whether they were paid within a given time frame.

return $dates->map(function ($item, $key) use ($interval) {
    $bills = DB::table('bills')
    ->where('provider_id', Auth::user()->company()->first()->id)
    ->whereBetween(
        'date_paid', [$item, $this->returnRangeFromInterval($item, $interval)]
    )
    ->where('status', 'paid')
    ->get();
    return $bills->pluck('amount_due')->sum();
});

That date_paid attribute is stored as UTC, but to return an accurate sum, I need to shift that date to a user's timezone—which I have stored on the User object. How could I accomplish this in the collection above?

It looks as though I can use a MYSQL method called convert_tz if absolutely necessary, but I'm interested first and foremost in the "Laravel Way".

  • 写回答

1条回答 默认 最新

  • doumi1852 2017-01-30 15:10
    关注

    Collections to the rescue. I was able to use map to modify the attribute in question, and then return a collection of bills with that modified attribute. Also reduced the number of queries I was making, too.

    $bills = DB::table('bills')
        ->where('provider_id', Auth::user()->company()->first()->id)
        ->where('status', 'paid')
        ->get();
    
    $adjustedBills = $bills->map(function ($bill, $key) {
        $bill->date_paid = Carbon::parse($bill->date_paid)->timezone('America/New_York')->toDateTimeString();
        return $bill;
    });
    
    return $dates->map(function ($item, $key) use ($interval, $adjustedBills) {
        return $adjustedBills->filter(function ($date, $key) use ($item, $interval) {
            return $date->date_paid >= $item && $date->date_paid <= $this->returnRangeFromInterval($item, $interval);
        })->pluck('amount_due')->sum();
    })->flatten();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害