I have a relationship many-to-many. I need to fetch all tags with parent id. For example it can look like this:
[
{ article_id: 1, id: 1, name: "tag 1" },
{ article_id: 1, id, 2, name: "tag 2" },
{ article_id: 2, id: 1, name: "tag 1" }
]
Look that tag 1 is two times for two articles. Propably I can make loop inside loop but it doesn't look proffesional. Could you show me the best solution of this problem?
@Edit: I created this code:
public function articles(){
$article = [];
$allArticles = Articles::all();
foreach($allArticles as $key => $a){
$obj = new \stdClass();
foreach($a->tags as $t){
$obj->article_id = $a->id;
$obj->name = $t->name;
array_push($article, $obj);
}
}
return json_encode($article);
}
But it doesn't work like I want. It display only one tag for one article, not all. Any idea?