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

后端 未结 4 1842
一生所求
一生所求 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

    In your SpentTime model, you are able to create accessors which are functions that can be used here to query the sum a day of all relating records:

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

    Here, we create two accessors, one to get the daily spent time and another to get the daily percentage, for all records based on relating task_category.

    There can be called using the following:

    $dailySpentTime = SpentTime::find($id)->dailySpentTime;
    
    // or within your blade template
    
    {{ $spentTime->dailySpentTime }}
    

    Update

    Within your controller, as you no longer have to run any calculations upon saving, you can do the following:

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

    Make sure to delete your custom findOrCreate() method which is currently overriding the laravel version.

    Hopefully this helps.

提交回复
热议问题