mardi 27 décembre 2016

Object only able to retrieve a single many-to-many relationship when two are defined

I have a model, "Tag", which has two many-to-many relationships, to "Post" and "Clue." I have two pivot tables (post_tag and clue_tag) and have defined functions to retrieve each of these ($tag->posts and $tag->clues - both work). However, when trying to display search results on a tag, only one set of results is retrieved. Here is my code:

$tag = Tag::where('name', $term)->firstOrFail();
$posts = $tag->posts;
$clues = $tag->clues;

If I run that code, only $posts has actual values- $clues is empty. However, if I run the following instead:

$tag = Tag::findOrFail($id);
$posts = $tag->posts;
$clues = $tag->clues;

then only $clues has results, and $posts is empty. If I run the following:

$tag = Tag::where('name', $term)->firstOrFail();
$clues =Tag::findOrFail($id)->clues;
$posts = Tag::where('name', $term)->firstOrFail()->posts;

then $clues and $posts are both populated. I was reading through the documentation and saw that you can have "Many To Many Polymorphic Relations" and only use a single table to track multiple sets of many-to-many relationships, so perhaps this is the way to go, but I still would like to understand what I am missing- why my existing set-up doesn't work. I should mention that I am new to Laravel (this is my first project), and to frameworks/ORM in general. I am using Laravel 5.3.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire