无法根据基于相同类别的输入正确计算数据
问题描述:
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
calculation does not match the input value
答
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'));
}