DutchPrince
DutchPrince

Reputation: 363

Eager load a relationship with subquery join

i have to join a table that has relations with another table and return the result to my view in readable data and display the correct data for each user. This is my code in the controller.

This works but the data from the relations are missing, what am i doing wrong?

    $GetUsers = User::groupBy('id');

    $all = OngoingTasks::with(['tasksdata', 'taskstatus'])->joinSub($GetUsers, 'users', function ($join) {
        $join->on('ongoing_tasks.user_id', '=', 'users.id');
    })->get();

OngoingTasks has a One to Many relation with taskstatus and a One to One relation with taskdata.

User has a One to many with OngoingTasks.

Upvotes: 0

Views: 249

Answers (1)

nakov
nakov

Reputation: 14288

If an OngoingTask belongs to one user then in the OngoingTask model add this:

public function user()
{
    return $this->belongsTo(User::class);
}

And you can change the query to this:

OngoingTasks::with(['tasksdata', 'taskstatus', 'user'])->get();

If you want to get OngoingTasks based on the user ids even though the approach above would do the same, but just in case you filter for couple of users, do this instead:

$userIds = User::pluck('id');

$all = OngoingTasks::with(['tasksdata', 'taskstatus', 'user'])->whereIn('user_id', $userIds)->get();

Upvotes: 1

Related Questions