princeoo7
1 month ago

Eloquent with, withCount gives 12 as total records but the function with groupby on date gives 9

Posted 1 month ago by princeoo7

I have 3 tables, Users, Tasks, TasksSession.

what I am trying to find is total session conducted and total days the user was involved in that task based on created_at group by statement.


    User::with(['Task','TotalSessionsGroupByDate'])->withCount(['TotalSessions','TotalSessionsGroupByDate'])->whereId(2)->first(),


With the above total_sessions_group_by_date_count = 12 and total_sessions_group_by_date_count = 9 records in an array.

function code for the TotalSessionsGroupByDate is as followed


    public function TotalSessionsGroupByDate(){
        return $this->hasMany(TaskSession::class)->groupBy('created_at');
    }

I have the total number of the session conducted / attendance but how to get the total number of days irrelevant to sessions. as per the example, total_sessions_group_by_date_count should be 9 and not 12 total_sessions_group_by_date_count.

the only solution that i was as of now, able to come up is as below:


$user = User::with(['TaskIssues','TotalSessionsGroupByDate'])
                        ->withCount(['TotalSessions'])
                        ->whereId(16)->first();
        $user->TotalSessionsGroupByDate = $user->TotalSessionsGroupByDate->count();

any better way to do the same in model?

Please sign in or create an account to participate in this conversation.