ds342222 2018-10-24 01:52
浏览 57
已采纳

无法根据基于相同类别的输入正确计算数据

Model

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

    $spent_time = SpentTime::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   = SpentTime::where('task_category',$task_category)
                                    ->sum('daily_spent_time', $spent_time->daily_spent_time , $fromDate);
        $spent_time['spent_time'] = $spent_time->spent_time + $spent_time->daily_spent_time;

        $spent_time->percentage   = SpentTime::where('task_category',$task_category)
                                    ->sum('daily_percentage', $spent_time->daily_percentage, $fromDate);
        $spent_time['percentage'] = $spent_time->percentage  + $spent_time->daily_percentage;
        return $spent_time->update($data);
    }
}

when creating new data with the same category, and inputting the data value, it should be able to calculate the data correctly, but this cannot

enter image description here

calculation does not match the input value

enter image description here

  • 写回答

1条回答 默认 最新

  • douxie5930 2018-10-31 02:34
    关注

    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 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'));
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?