public static function findOrCreate($plan_id, $data)
{
$fromDate = Carbon::now()->subDay()->startOfWeek();
$nowDate = Carbon::now()->today();
$spent_time = static::where('plan_id', $plan_id)->first();
if (is_null($spent_time)) {
return static::create($data);
}else{
$new_spent_time = SpentTime::find($plan_id);
$task_category = $new_spent_time->task_category;
$new_spent_time->task_category = (['{task_category}' => $task_category,
'{daily_spent_time}' => $new_spent_time->daily_spent_time,
'{daily_percentage}' => $new_spent_time->daily_percentage,
'{spent_time}' => $new_spent_time->spent_time,
'{percentage}' => $new_spent_time->percentage, $new_spent_time->task_category]);
$new_spent_time->spent_time = $new_spent_time::where('task_category',$task_category)
->sum('daily_spent_time', $new_spent_time->daily_spent_time , $fromDate);
$new_spent_time['spent_time'] = (int)$new_spent_time->spent_time + $spent_time->daily_spent_time;
$new_spent_time->percentage = $new_spent_time::where('task_category',$task_category)
->sum('daily_percentage', $new_spent_time->daily_percentage, $fromDate);
$new_spent_time['percentage'] = (int)$new_spent_time->percentage + $spent_time->daily_percentage;
return $spent_time->update($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'));
}
with problems, when saving create new data then an error "Trying to get property of non-object"
but there is one data that can save when creating new data, but cannot yet calculate the data, and while the other categories cannot be like that, instead the error
what should be corrected from this problem?
Так что нужно улучшить? извините, я все еще учусь, так что все еще не понимаю вашей точки зрения.
Структура немного сложна для понимания, я посмотрел, но запутался, где вы использовали предложения where(). Вы можете запустить where() на одной записи.
так что поменять?
Не могли бы вы обновить свой вопрос своей моделью и модельными отношениями, чтобы я понял, чего пытаетесь достичь.
Разве не в этой строке $task_category = $new_spent_time->task_category; проблема в вопросе? Я полагаю, что возвращаемое значение $new_spent_time равно нулю или что-то вроде не объект. Я думаю, вам может понадобиться проверить if ($new_spent_time !== null) или другие проверки ... как насчет этого?
@thisiskelvin при создании новых данных с той же категорией данные о потраченном времени должны рассчитываться с предыдущими данными (той же категории), которые есть в таблице TST, а также с процентным соотношением
@Qiuwatobi $ new_spent_time есть данные
Я бы сказал, что вам не нужно добавлять это в запись базы данных. Это можно рассчитать с помощью другой модельной функции. Причина в том, что у каждой записи в какой-то момент не будет одинакового времени, поскольку она не была сохранена. При необходимости с помощью осциллографа можно будет рассчитать процент time and . Я создам пример для дальнейшего объяснения.
@thisiskelvin спасибо, жду ответа
Это так? public function getDailySpentTimeAttribute() { return self::where('task_category', $this->task_category['daily_Spent_time'] == 'daily_spent_time') ->get() ->sum('daily_spent_time'); }






public static function findOrCreate($plan_id, $data)
{
$fromDate = Carbon::now()->subDay()->startOfWeek();
$nowDate = Carbon::now()->today();
$spent_time = static::where('plan_id', $plan_id)->first();
if (is_null($spent_time)) {
return static::create($data);
}else{
$new_spent_time = SpentTime::first();
$task_category = $new_spent_time->task_category;
$new_spent_time->task_category = (['{task_category}' => $task_category,
'{daily_spent_time}' => $new_spent_time->daily_spent_time,
'{daily_percentage}' => $new_spent_time->daily_percentage,
'{spent_time}' => $new_spent_time->spent_time,
'{percentage}' => $new_spent_time->percentage, $new_spent_time->task_category]);
$new_spent_time->spent_time = $new_spent_time::where('task_category',$task_category)
->sum('daily_spent_time', $new_spent_time->daily_spent_time , $fromDate);
$new_spent_time['spent_time'] = (int)$new_spent_time->spent_time + $spent_time->daily_spent_time;
$new_spent_time->percentage = $new_spent_time::where('task_category',$task_category)
->sum('daily_percentage', $new_spent_time->daily_percentage, $fromDate);
$new_spent_time['percentage'] = (int)$new_spent_time->percentage + $spent_time->daily_percentage;
return $spent_time->update($data);
}
}
В вашей модели SpentTime вы можете создать аксессуары - функции, которые можно использовать здесь для запроса суммы всех связанных записей за день:
public function getDailySpentTimeAttribute()
{
return self::where('task_category_id', $this->task_category_id)
->get()
->sum('daily_spent_time');
}
public function getDailyPercentageAttribute()
{
return self::where('task_category_id', $this->task_category_id)
->get()
->sum('daily_percentage');
}
Здесь мы создаем два accessors, один для получения ежедневного затраченного времени, а другой - для получения ежедневного процента для всех записей на основе связанных task_category.
Вызвать можно с помощью следующего:
$dailySpentTime = SpentTime::find($id)->dailySpentTime;
// or within your blade template
{{ $spentTime->dailySpentTime }}
В вашем контроллере, поскольку вам больше не нужно выполнять какие-либо вычисления после сохранения, вы можете сделать следующее:
public function store(Request $request)
{
$spent_time = SpentTime::findOrCreate($request->get('plan_id'), [
'task_category' => $request->get('task_category'),
'reason' => $request->get('reason'),
]);
return redirect()->route('real.index', compact('spent_time'));
}
Обязательно удалите свой собственный метод findOrCreate(), который в настоящее время переопределяет версию laravel.
Надеюсь, это поможет.
есть ли дополнительный вызов к контроллеру?
В методе контроллера store() необходимо только обычное сохранение. dailySpentTime можно вызвать на любой записи SpentTime.
Обновлено. Пожалуйста, дайте мне знать, если вы понимаете.
ошибка Call to a member function getDailySpentTimeAttribute() on boolean
Вы можете dd()$spent_time, чтобы увидеть, что отголоски.
Какие данные вы видите?
Взгляните здесь: laravel.com/docs/5.7/… Вам нужно append новые значения для ответа json.
Это так?
Нет. И вы возвращаете время сервера в функциях. Найдите время, чтобы узнать о средствах доступа и других функциях для laravel. Это обязательно поможет в будущем.
может создавать новые данные, если это сделать, но не может рассчитывать данные по той же категории public function getDailySpentTimeAttribute($value) { return $this->attributes['daily_spent_time'] = ucfirst($value); }
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);
}
}
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'));
}
$new_spent_timeвообще не сохраняется. Вы также создаете обновление какproperties, так и массиваkeys. Выбери один.