I'm trying to make the relationship between 3 tables in laravel. With 2 tables I got it, thanks to the help of the forum, but I can not make it work with 3 tables. the relationship is as follows: I have 3 tables:
News, Photos and Unit (school units)
tabela noticia -> id_noticias
tabela fotos-> id_fotos e id_noticias
tabela noticia_unidade
The news relationship with photos is ok: on the main page there are 2 news items and a photo of each. Now I need to be filtered by unit: In the page of the faculty only appears the news of the unit 2, for example.
Following the Models and Controllers:
Controller
public function index(){
$not_faculdade = Noticia::with(['foto' => function($query){
$query->get()->first();
}])
->with(['unidade' => function($query2){
$query2->where('id_unidade','2')->get();
}])
->orderBy('id_noticias','DESC')
->take(2)
->get();
// dd($not_faculdade);
return view('pages_faculdade.noticia')->with('not_faculdade',$not_faculdade);
}
Models
class Noticia extends Model
{
protected $table = 'noticias';
protected $primaryKey = 'id_noticias';
public $timestamps = false;
protected $dates = ['data'];
protected $fillable =[
'texto',
'titulo',
'legenda',
'pasta',
'subtitulo',
'evento',
'titulo_evento'
];
public function foto()
{
//return $this->hasMany(Foto::class);
return $this->hasMany('App\Foto','id_noticia','id_noticias');
}
public function unidade()
{
//return $this->hasMany(Foto::class);
return $this->belongsTo('App\Unidade','id_noticias','id_noticia');
}
}
class Unidade extends Model
{
protected $table = 'noticia_unidade';
// protected $primaryKey = 'id_noticia, id_unidade';
public $timestamps = false;
protected $dates = ['deleted_at'];
protected $fillable = [
'id_unidade',
'id_noticia'
];
public function noticias()
{
return $this->hasMany('App\Noticia','id_noticias','id_noticia');
}
}
View
@foreach ($not_faculdade as $key=> $not)
<div class="col-md-6">
<div class="panel-heading">
<div class="painel_foto"><img src={{asset('public/'.$not->foto[0]->endereco)}}></div>
<h4>{{ $not->titulo }}</h4>
<p align="justify">
<a href="#" class="noticia">
{{$texto = substr($not->texto,0,150)." ..."}}
</a>
</p>
</div>
</div>
@endforeach
As I said, the 2 news items with the "cover" photo appear normally, but the filter does not work.
If I give dd($not_faculdade)
, the seemingly right relationships are shown!
What could be wrong?
Follow relationship (I did it the way I could because I do not know how to play with these tools)
1 news has several photos belonging to a single news 1 news item can appear in multiple units and each unit can contain various news