Home > OS >  Use whereHas and query pivot table
Use whereHas and query pivot table

Time:11-17

I have 3 table: tasks, users, group, and a pivot table group_user.

A task has user_id, group_id

A group_user pivot table has user_id, group_id

I want to query the tasks if the task belongs to a group of the user.

I don't want tasks from groups that the user doesn't belong to.

What I have so far:

public function index()
    {
        $userId = Auth::user()->id;

        return TaskResource::collection(
            Task::
                latest()
                ->whereHas('group', function($query) use($userId) {
                    $query->where('group_id', '=', $userId); // = is wrong 
                })
                ->get()
        );
    }

This gives me empty results, I tried to think about it but my head hurts

CodePudding user response:

Ive not tested this but i imagine you could nest the where has and use something like this in your whereHas block:


$query->whereHas('user', function($q2) use ($userId) {
    $q2->where('user_id', $userId);
});

CodePudding user response:

You want to get the tasks that are related to the group (or groups) of a user.

I supposed the relation name between the user table and the group table is 'users', in the Group model.

$userId = auth()->id();   

$tasks = Task::latest()
                   ->whereHas('group', function($query) use ($userId) {
                        $query->whereHas('users', function($query) use ($userId) {
                            $query->where('user_id', $userId);
                        });
                    })
                    ->get();
  • Related