“试图获取非对象的属性”
模型
在创建新数据并要保存时,如上所述发生错误
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);
$request['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);
$request['percentage'] = (int)$new_spent_time->percentage + $spent_time->daily_percentage;
$new_spent_time->save();
return $spent_time->update($data);
}
答案 0 :(得分:0)
"Trying to get property of non-object"
表示该属性不存在
将您的find
更改为findOrFail
$new_spent_time = SpentTime::findOrFail($plan_id);
这样,laravel在数据库中找不到记录时将返回错误。
另一种方法是检查查询是否成功:
$new_spent_time = SpentTime::find($plan_id);
if($new_spent_time){
$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);
$request['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);
$request['percentage'] = (int)$new_spent_time->percentage + $spent_time->daily_percentage;
$new_spent_time->save();
return $spent_time->update($data);
}else{
return 'no result found';
}
答案 1 :(得分:0)