Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

239
Vistas
Laravel Eloquent equivalent of a QueryBuilder query

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?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

// 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!

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda