I have a many to many relationship with a pivot table.
goods
id | title | ...
tags
id | title | ...
good_tag
id | good_id | tag_id | ...
How correctly retrieve all goods and their tags in laravel?
Thanks
With Eager Loading
$goods = Good::with('tags')->get();
foreach ($goods as $good) {
// each goods
echo $good->title;
foreach ($good->tags as $tag) {
// each tag for that goods
echo $tag->title;
}
}
Each returned Good model will have its collection of Tags attached.
Ok, first lets write the relationships in your models:
Good Model( representing goods table)
public function getTags()
{
return $this->belongsToMany('Tag','good_tag','good_id','tag_id');
}
Tag Model (representing tags table), this is reverse relationship to get goods for a specific tag
public function getGoods()
{
return $this->belongsToMany('Good','good_tag','tag_id','good_id');
}
Now to retrieve all goods and their tags here's the code:
$goods=Good::All();
foreach($goods as $good)
{
echo $good->title;
echo "Tags: ";
foreach($good->getTags as $tag)
{
echo $tag->title." ";
}
}