douguang9014 2018-10-18 01:58
浏览 26
已采纳

在laravel中创建新数据时,无法按类别保存计算数据

Model SpentTime

I am unable save calculation data by category when create new data in laravel

public static function findOrCreate($plan_id, $data)
{
    $fromDate = Carbon::now()->subDay()->startOfWeek()->toDateString();
    $nowDate = Carbon::now()->today()->toDateString();

    $spent_time = static::where('plan_id', $plan_id)->first();

    if (is_null($spent_time)) {
        return static::create($data);
    }else{
        $task_category = SpentTime::where('task_category', $spent_time->task_category)->get();
        $create_spent_times = SpentTime::where('task_category', $spent_time->task_category)->sum('daily_spent_time', $fromDate);
        $request['spent_time'] = (int)$create_spent_times + $spent_time->daily_spent_time;

        $create_spent_times = SpentTime::where('task_category', $spent_time->task_category)->sum('daily_percentage', $fromDate);
        $request['percentage'] = (int)$create_spent_times + $spent_time->daily_percentage;

        $spent_time->save();
        return $spent_time->update($data);
    }
}

TrackerController

This is the controller function to store data:

public function store(Request $request)
{      
    $spent_time = SpentTime::findOrCreate($request->get('plan_id'), [
        'plan_id' => $request->get ('plan_id'),
        'daily_spent_time' => $request->get ('daily_spent_time'),
        'daily_percentage' => $request->get ('daily_percentage'),
        'reason' => $request->get ('reason')
    ]);
    return redirect()->route('real.index', compact( 'spent_time'));
}
  • 写回答

2条回答 默认 最新

  • dox19458 2018-10-31 02:41
    关注

    Model

    public static function findOrCreate($plan_id, $data)
    {
        $spent_time = static::where('plan_id', $plan_id)->first();
        $task_category = $spent_time->task_category;
    
        if (is_null($spent_time)) {
            return static::create($data);
        }else{
            $spent_time['spent_time'] = $spent_time->spent_time + $spent_time->daily_spent_time;
            $spent_time['percentage'] = $spent_time->percentage  + $spent_time->daily_percentage;
    
        return $spent_time->update($data);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求指导ADS低噪放设计
  • ¥15 CARSIM前车变道设置
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存