0
votes

In my project I have 3 models: Snapshots, Users, Teams

A snapshot can have a user_id. A user can belongsto multiple Teams. (via a pivot table team_user)

I want to list all snapshots per teams.

Something Like

Team 1 - Snapshot 2 - Snapshot 4 - Snapshot 9

Team 2 - Snapshot 1 - Snapshot 3

Alongside this I want Teams to be limited by those that belongTo the authenticated user.

So if UserA is belongsTo Teams 3 and Team 6. I would like to have only those outputted.

I can list the snapshots which have a relationship via users with this eloquent query:

Auth::user()->teams()->with(['users.snapshots'])->get();

This gives me Teams > Users > Snapshots. How can I transform this so I just get Team > Snapshots

I don't think I can use hasManyThrough because I use pivot table for Teams to Users (eg. team_user table).

Thanks

1

1 Answers

0
votes

I was advised on a help slack my options were:

  1. Write a Query Builder query
  2. Use a package
  3. Write a new relation method

I chose option 2 and used this package: https://github.com/staudenmeir/eloquent-has-many-deep

and added the following to my Team.php Model:

public function snapshots()
{
    return $this->hasManyDeep(Snapshot::class, ['team_user', User::class]);
}

This allows relationships with unlimited intermediate models (including via a pivot table, which is how the code above works).