Skintest
Skintest

Reputation: 174

Laravel relationship query - get all completed projects

Looking for some advice on creating an eloquent query.

I have 3 tables

A project has tasks, and in usertasks we save the task and user id so we know it has been completed by the user. Now I need to query all projects that have been completed by the user, so projects that have tasks where all tasks for that project have been completed.

I can't seem to wrap my head around it, I am trying to create a scope for this.

public function scopeisCompleted($query)
{
    $query = $query->whereHas('userTasks', function ($query) {
        $query->where('user_id', '=', Auth::user()->id);
    })->get();

    return $query;    
}

I can't seem to get my head around how to make sure all tasks for that project are completed by the user.

Any advice on moving forward?

Upvotes: 2

Views: 674

Answers (1)

martincarlin87
martincarlin87

Reputation: 11052

I think you'd need something like this:

public function scopeisCompleted($query)
{
    $query = $query->whereHas('userTasks', function ($query) {
        $query->where('user_id', '=', Auth::user()->id)
            ->whereHas('task', function ($query) {
                $query->where('completed', 1);
            });
    })->get();

    return $query;    
}

So as long as the task relationship is setup for the UserTask model and the column is completed, if not change it to the correct one.

I just read your question in more detail, if you need to check that all tasks are completed then that would be a bit more complicated, the query would need to find how many tasks there are and if that number matches the total completed tasks.

Update

I think I understand a bit more now on what you're trying to do:

public function scopeisCompleted($query)
{
    $query = $query->with('tasks', 'userTasks')->whereHas('userTasks', function ($query) {
        $query->where('user_id', '=', Auth::user()->id);
    })->get();

    return $query;    
}

as mentioned in the comment, I'm not sure what model this scope is being used on so this might still be incorrect, but here I've added the ->with('tasks') so that once the query results have been returned, the tasks for the project can be compared to the user completed tasks for the project, although it should still be possible to do this in the query rather than in PHP.

if (count($results->tasks)) == count($results->userTasks)) {
    // complete
}

I will need to think about it later, I might have the wrong syntax for what you're trying to do and the with might need to be something like ->with('tasks.userTasks').

Upvotes: 1

Related Questions