简体   繁体   English

如何在雄辩的Laravel中与三个表进行协商

[英]how to make consultation with three tables in Eloquent Laravel

I have three tables that are the following users , mapas , marcadores 我有以下三个用户表, mapasmarcadores

A user has several mapas 一个用户有几个mapas

a mapa has several marcadores 一个mapa有几个marcadores

What I'm trying to do is show the marcadores that belong to the mapas of the user who has logged in. 我正在试图做的是显示属于谁已经登录的用户的一举成名marcadores。

this are the tables and relationship 这是表格和关系

在此处输入图片说明

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'));
}

thanks for your help 谢谢你的帮助

You are trying to get all the mapas id first and then filter marcadores according to those id's. 您正在尝试先获取所有mapas ID,然后根据这些ID过滤marcadore Try using the code below for that: 为此,请尝试使用以下代码:

public function index()
{
    $mapas = Mapa::orderBy('id', 'DESC')->where('user_id', auth()->user()->id)->pluck('id')->toArray();
    $marcadores = Marcador::orderBy('id', 'DESC')->whereIn('mapa_id', $mapas)->get();
    return view('user.marcadores.index', compact('marcadores'));
}

You can use JOINS for this. 您可以为此使用JOINS Try the next code (maybe the syntax is not the correct one, but take the idea): 尝试下一个代码(也许语法不是正确的代码,但是可以理解一下):

public function index()
{
    $marks = DB::table('mapas')
             ->join('marcadores', 'marcadores.mapa_id', '=', 'mapas.id')
             ->where('mapas.user_id', auth()->user()->id)
             ->select('marcadores.*')
             ->orderBy('marcadores.id', 'DESC')
             ->get();                  

    return view('user.marcadores.index', compact('marks'));
}

The easiest and Laravel standard way to do this is create a hasManyThrough relationship from User to Marcadores 最简单的Laravel标准方法是从UserMarcadores建立hasManyThrough关系

UserModel 的usermodel

class User extends Model
{
    public function marcadores()
    {
        return $this->hasManyThrough(Marcadores::class, Mapas::class);
    }
}

Controller 调节器

public function index()
{
    $marcadores = auth()->user()->marcadores;
    return view('user.marcadores.index', ['marcadores' => $marcadores]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM