Good morning as always I have problems with relationships. I have three tables and one of them acts as a pivot. What I want to get an iteration of the categories to which the article belongs, in the iteration of articles.
my tablearticles
go | Title | Photo |
---|---|---|
1 | news name 1 | photo.jpg |
two | news name 2 | photo.jpg |
my tablecategory_blogs
go | worth | slug |
---|---|---|
1 | Nutrition | nutrition |
two | Training | training |
my tableenlaza_categorias
go | id_category | id_article |
---|---|---|
1 | two | 1 |
two | 1 | two |
two | 1 | two |
This is the query in my controller:
$noticias = articles::where('destacado', 0)->where('estado', 1)->orderBy('id', 'desc')->paginate(8);
Then I iterate the items in my view
@foreach ($noticias as $item)
.....
<div>
//Aquí quiero sacar los nombres de la categoría
@foreach ($item->categorias as $item2)
<span>{{ $item2->id_category }}</span>
@endforeach
</div>
.....
@endforeach
Modelarticles
protected $table = 'articles';
protected $primaryKey='id';
public function categorias()
{
return $this->hasMany('App\EnlazaCategoria', 'id_article');
}
ModelcategoryBlog
class categoryBlog extends Model
{
//Lo tengo vacio
}
ModelEnlazaCategoria
protected $table = 'enlaza_categorias';
protected $primaryKey='id';
public function categorias()
{
return $this->belongsTo('App\categoryBlog', 'id');
}
If the relationship is many-to-many , then:
Articles
andcategoryBlog
must have a declared relationship of the typebelongsToMany
enlaza_categorias
does not require an associated model and if you are going to use it then you must stick to what Laravel indicatesHaving said the above, we can then:
Model articles
Model categoryBlog
We load the relationships associated with the items passing the name of the relationship in the model as an argument
articles
It is important to clarify that for this answer I did not consider the use of a model for the intermediate table