Hi! I think the last example you gave is similar to what is explained here: http://softonsofa.com/tweaking-eloquent-relations-how-to-get-latest-related-model/ , but with a many to many relationship. You can try the solution proposed to "iog3" (at the bottom of the page, the first one). Let me know if it solves your problem! Hope it does.
Aug 27, 2015
9
Level 5
Eager Load latest relation on many to many relationships
Hey,
I've got a problem that seemed quite simple at first but nobody seems to have found an answer yet.
I have two classes: Articles and Tags in a many to many relationship. What I am trying to do is accessing the latest Article foreach Tag in an efficient way.
I tried the following approaches:
$tags = Tag::with(['article' => function($query) {$query->latest()->take(2); }])->get();
But this only returns two articles for the whole query and not for each tag.
Then I tried to add a new accessor in the Tag class.
public function latestArticle()
{
return $this->belongsToMany('App\Article')->latest()->take(2);
}
But I end up with the same problem.
What I am ultimately trying to achieve is listing all the tags paginated and ordered by the number of articles that are linked to them, with the two latest articles for each of those tags.
Does anybody have an idea how to achieve this? thanks
Please or to participate in this conversation.