Laravel 5.2 | request from many to many to one

I am currently working on a project with multiple domains and languages ​​where videos are reused with different names and descriptions.

My tables related to this relationship issue look like

posts >- videos >- videos_tags -< tags id id id id domain_id video_id video_id tag_id 

Of course, I created models: Post, Video and Tag with all the necessary relationships.

What I'm trying to do is get all the posts on my tag model and maintain the pagination () functionality.

I can get all the tags associated with the message through the video module. However, when I try to make the return trip, I do not seem to retain the functionality of pagination (). I tried a lot, but I can not find the right solution.

The closest (I think) I was with this piece of code:

 // App\Models\Tag public function posts() { $posts = []; foreach ($this->videos as $video) { foreach ($video->posts as $post) { if (!array_key_exists($post->id, $posts)) $posts[$post->id] = $post; } } return \Illuminate\Database\Eloquent\Collection::make($posts); } 

Any suggestions or articles that I skipped while searching for an answer are welcome :)

+2
php eloquent laravel
source share
2 answers

Immediately after I asked this question, I had a moment of eureka and found a solution. The way to do this is not by obtaining Post models using the Tag model, but using the Post model itself.

This is what I did:

 // App\Models\Tag public function posts() { return Post ::select('posts.*') ->join('videos', 'posts.video_id', '=', 'videos.id') ->join('videos_tags', 'videos.id', '=', 'videos_tags.video_id') ->join('tags', 'videos_tags.tag_id', '=', 'tags.id') ->where('tags.id', $this->id); } 

This solves the query problem from many to many to one relationship and preserves the eloquents functionality before executing the query.

+2
source share

In your message model, you can define what is called a scope.

 class Post { /** * Limit query to posts related to a given tag id. * * @param Builder $query The original query * @param Integer $tag_id The tag id to filter for * @return Builder The query with an additional where */ public function scopeHasTag($query, $tag_id) { // assumes that there is a 'tags' relation return $query->whereHas('tags', function($tags_query) use ($tag_id) { return $tags_query->where('id', $tag_id); }); } } 

This scope will allow you to execute a query similar to the following ( hasTags laramagically retrieved from scopeHasTags ).

 $posts = Post::query()->hasTag(10); // All posts related with tag id 10 return $posts->paginate(); 

Here is the official documentation on request areas: https://laravel.com/docs/5.2/eloquent#local-scopes

+1
source share

All Articles