Laravel Eloquent equivalent of a QueryBuilder query

Viewed 95

I have a Laravel 7 project and this database structure:

 races      participants      bibs      coords
-------    --------------    ------    --------
 id         id                id        id
            race_id                     bib_id
            bib_id                      [...]

The relations are:

1 race        =>  N participants  ( races.id = participants.race_id )
1 participant =>  1 bib           ( participants.bib_id = bibs.id )
1 bib         =>  N coords        ( bibs.id = coords.bib_id )

So it also means that: participants.bib_id = coords.bib_id

I want to get all the Coords related to a specific Race. The way I did is using query builder like this:

class Race extends Model
{
    public function getCoords()
    {
        return Coord::join('participants', 'participants.bib_id', '=', 'coords.bib_id')
            ->where('participants.race_id', $this->id)->select('coords.*')->get();
    }
}

Here I can do that:

$coords = Race::find(1)->getCoords();

It's working as expected, but I'm looking for a way to do it using Eloquent so that it would be easier to chain with more relations and stuff.
I tried a lot of things with belongsToMany and hasManyThrough but nothing worked. I wonder if that is even possible?

1 Answers
// Race
public function participants()
{
    return $this->hasMany(Participant::class);
}

// Participant
public function bib()
{
    return $this->belongsTo(Bib::class);
}
public function race()
{
    return $this->belongsTo(Race::class);
}

// Bib
public function coords()
{
    return $this->hasMany(Coord::class);
}

// Coord
public function bib()
{
    return $this->belongsTo(Bib::class);
}


Now, what you want is to find coords for a given race.

$race = Race::find($id)->with('participants.bib.coords');


Now, to extract coords from it.

$coords = $race->participants->map(function($participant){
              return $participant->bib->coords;
          });


Keep me posted in the comments below. Cheers!

Related