无法显示具有多对多关系的数据 Laravel 8

时间:2021-06-30 15:50:13

标签: php laravel laravel-8

我有两个表,personasespecialidades 在多对多的关系中,我将发布我的数据库模型如何显示表的属性。

Database model

如您所见,我有 personas 表关联到 especialidades 表和数据透视表 persona_especialidad

阅读文档我的关系在模型中应该是这样的

class Persona extends Model
{
    ///.....
    public function Persona_especialidad(){
        return $this->belongsToMany(Especialidades::class,'persona_especialidad','idEspecialidad','idPersona');
    }
}

我试图在我的视图中显示 personas 的属性为 4 的行以及它们关联的 idTipoPersonanombre。< /p>

这是我现在在视图中的代码。

especialidades

在这个视图中,$medico 来自这个函数的 @extends('layouts.app') @section('content') <h1>Gestión Médicos</h1> <div class="container"> <div class="container my-5"> <a class="btn btn-primary btn-lg text-body" href="{{route('medico.create')}}">Registrar Médico</a> </div> <table class="table table-bordered table-hover"> <tr class="info"> <th>Nombre</th> <th>Apellido</th> <th>Cedula</th> <th>Email</th> <th>Especialidades</th> <th>Teléfono</th> <th>Dirección</th> <th>Ciudad Residencia</th> <th>Fecha de Nacimiento</th> <th>Género</th> <th colspan="2">Opciones</th> </tr> @foreach ($medicos as $medico) <tr> <td>{{$medico->nombre}}</td> <td>{{$medico->apellido}}</td> <td>{{$medico->cedula}}</td> <td>{{$medico->email}}</td> <td> @foreach ($medico->Persona_especialidad as $especialidad) {{$medico->Persona_especiaidad}} {{$especialidad->nombre}} @endforeach </td> <td>{{$medico->telefono}}</td> <td>{{$medico->direccion}}</td> <td>{{$medico->ciudadResi}}</td> <td>{{$medico->fechaNacimiento}}</td> <td>{{$medico->genero}}</td> <td><a href="{{route('medico.edit', $medico->id)}}">Editar</a></td> <td><a href="{{route('medico.borrar', $medico->id)}}">Borrar</a></td> </tr> @endforeach </table> </div> @endsection ,我将在下面发布

PersonaController

我没有收到任何错误,而是在应该显示值的 public function mostrarMedicos(){ $medicos = Persona::where('idTipoPersona', 4)->where('estado',True)->get(); return view('gestionMedicos',compact('medicos')); } 中没有得到任何结果。发个图吧。

View

我是 Laravel 的新手,所以也许我没有正确理解有关多对多关系的文档。我该怎么做才能显示来自与 td 关联的 especialidades 的数据?

0 个答案:

没有答案