staudenmeir / eloquent-has-many-deep

Laravel Eloquent HasManyThrough relationships with unlimited levels
MIT License
2.67k stars 157 forks source link

I'm getting the results for all users - help please #221

Closed RobTrehy closed 11 months ago

RobTrehy commented 11 months ago

Hi, I'm struggling to get this right and probably need another set of eyes over it if you can please!

I have three models; User, Session, SessionLap

Users have many Sessions and each Session has many Users (via session_drivers table)

User has many SessionLaps (has user_id and session_id fields)

I have the following relationships

User Model

public function sessions(): HasMany
{
    return $this->hasMany(Session::class);
}

public function laps()
{
    return $this->hasManyDeep(
        SessionLap::class,
        ['session_drivers', Session::class],
        ['user_id', 'id'],
    );
}

Sessions Model

public function users()
{
   return $this->belongsToMany(User::class, 'session_drivers', 'session_id', 'user_id');
}

I'm trying to load the relationship with the following: Session::where('id', 1)->with(['users', 'users.laps'])->get();

However, whilst I can correctly see the Sesssion->Users, each User then has all laps with the session_id of 1 and the user_id is ignored.

RobTrehy commented 11 months ago

After looking over this, I can lazy load the data as I want it. But could it be loaded with relationships?

$sessions = Session::whereIn('id', [1,2,3])->with(['users'])->get();

foreach ($sessions as $session) {
    foreach ($session->users as $user) {
        $driver->laps = SessionLap::where('session_id', $session->id)->where('user_id', $user->id)->get();
    }
}
staudenmeir commented 11 months ago

Hi @RobTrehy, Unfortunately, it's not possible to get this result with a relationship.

RobTrehy commented 11 months ago

Thanks - I thought so once I took some time away and came back to it 🙂