how to calculate data by category when creating new data with the same category

后端 未结 4 1861
一生所求
一生所求 2021-01-17 01:02

Model

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


        
4条回答
  •  醉酒成梦
    2021-01-17 01:40

    Update Answer

    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);
        }
    }
    

    Controller

    public function index()
    {
        $spent_times = SpentTime::orderBy('task_category')->where('created_at', '>=', Carbon::today()->toDateString())->paginate(10);
        $user_stories = Plan::pluck('user_story', 'id');
        $real = new SpentTime;
    
        return view('reals.index', compact('spent_times', 'user_stories', 'real'));
    }
    
    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'));
    }
    

提交回复
热议问题