timmyc
timmyc

Reputation: 522

In Laravel Eloquent, select "whereIn" from parent table

In my Laravel project (with MySQL database), I have a few models: Time Entries, Tasks, and Projects.

Time Entries belong to Tasks

Tasks belong to Projects

so each table contains a column for the corresponding ID of its parent.

I have an array of Project IDs, and I am trying to select the time entries which, through their tasks, belong to those projects.

In other words, I'd like to be able to do something like this:

$timeEntries = TimeEntry::whereIn('project_id',$projectIds)->get();

But obviously, I get a column not found error, because all I've got in the time entries table is task_id rather than project_id.

Is there a way to select the desired time entries (based on the project IDs I have) in a single Eloquent query? Help much appreciated.

Upvotes: 0

Views: 1317

Answers (2)

Nehal Hasnayeen
Nehal Hasnayeen

Reputation: 1223

Add the following method in your Project model

public function timeEntries()
{
    return $this->hasManyThrough('App\TimeEntry' , 'App\Task');
}

now you can get all time entries of a project like below

$project = Project::find(id);
$project->timeEntries()->get();

Upvotes: 1

Sieabah
Sieabah

Reputation: 964

So the type of relation you're explaining is a through relation (http://laravel.com/docs/5.1/eloquent-relationships#has-many-through).

Instead of trying to head up the tree head down the tree from projects->tasks->time_entries.

Projects::whereIn($projectIds)->with('time_entries')->get();

The resulting collection will be projects with (should be at least) a field called time_entries in each project that have all the relevant times.

Upvotes: 0

Related Questions