V4n1ll4
V4n1ll4

Reputation: 6099

Laravel 5.1 has many through relationship

I have the following tables setup:

User
    - id

Timesheet
    - id
    - user_id

Users also have roles. A user can have an employee role or a supervisor role. Users can be assigned to supervisors, so I have setup the following relationship on the User model:

/**
 * The supervisors that are assigned to the user.
 *
 * @return Object
 */
public function supervisors()
{
    return $this->belongsToMany('App\Models\User\User', 'supervisor_user', 'user_id', 'supervisor_id')->withTimestamps();
}

The supervisor_user table is a pivot table and has data like so:

user_id    supervisor_id
1          5

The above means that the user with id of 1 is assigned to the supervisor with id of 5.

I now want to be able to get a list of Timesheets that belong to User who are assigned to a Supervisor.

I have tried setting up a relationship like so:

/**
 * Timesheets that belong to assigned users.
 *
 * @return Object
 */
public function supervisorTimesheets()
{
    return $this->hasManyThrough('App\Models\Timesheet\Timesheet', 'Costain\Models\User\User', 'id', 'user_id');
}

However, this results in the following SQL query which does not join my supervisor_user table in order to only return timesheets that belong to users who are assigned to this supervisor:

select `timesheet`.*, `user`.`id` from `timesheet` inner join `user` on `user`.`id` = `timesheet`.`user_id` where `user`.`id` = 1

Does anyone know how I can return timesheets that belong to users who are assigned to a specific supervisor?

Upvotes: 1

Views: 194

Answers (1)

patricus
patricus

Reputation: 62278

HasManyThrough can only be used with HasOne/HasMany relationships. It cannot be used with a many to many (BelongsToMany) relationship.

I think what you're really looking for is a whereHas() query:

$supervisor = User::find(5);
$timesheets = Timesheet::whereHas('user.supervisors', function ($query) use ($supervisor) {
    $query->where('id', $supervisor->id);
})->get();

Upvotes: 1

Related Questions