make consultation with three tables in Eloquent Laravel

2

I have three tables that are the following users , maps , bookmarks

  • A user has several maps
  • a map has several markers

What I am trying to do is show the markers that belong to the maps of the user who has logged in.

This is the function in the controller that I am working on:

public function index()
        {
            $mapas = Mapa::orderBy('id', 'DESC')->where('user_id', auth()->user()->id);
            $marcadores = Marcador::orderBy('id', 'DESC')->where('mapa_id');
            return view('user.marcadores.index', compact('marcadores'));
        }
    
asked by Talked 22.10.2018 в 16:47
source

2 answers

1

If you have the relationships established in the model you can do the query like this:

class Mapa extends Model
{
    /**
     * Get the comments for the blog post.
     */
    public function marcadores()
    {
        return $this->hasMany('TuModeloMarcadores');
    }
}

Mapa::with('marcadores')->orderBy('id', 'DESC')->where('user_id', auth()->user()->id);

And then you access the map markers like this

foreach ($mapas as $mapa) {
    $mapa->marcadores
}
    
answered by 24.10.2018 в 12:26
1

What you can do is load the marcadores when you look for the maps and then extract these to return them to view.

class Mapa extends Model
{
    /**
     * Obtener los marcadores.
     */
    public function marcadores()
    {
        return $this->hasMany(Marcadores::class);
    }
}

Then, on your controller:

public function index()
{
    $marcadores = Mapa::with('marcadores')
                     ->orderBy('id', 'DESC')
                     ->where('user_id', auth()->id()) // equivalente a auth()->user()->id
                     ->get()  // hasta acá ya cargamos los mapas con sus marcadores
                     ->flatMap(function ($mapa) {
                         return $mapa->marcadores;
                     });    // con esto estamos extrayendo los marcadores y compactando el array


    return view('user.marcadores.index', ['marcadores' => $marcadores]);
}

Important to note that ->get() will return a collection of objects. This collection is an instance of the Collection class, which allows you to use all of these useful methods with which you can map / transform / extract data, etc. This is why I used FlatMap .

    
answered by 25.10.2018 в 05:35