Laravel - Retrieve collections through two pivot tables
Laravel - Retrieve collections through two pivot tables
I'm currently struggling with the following issue in Laravel 5.6, let's say I have the following database tables:
I'm looking for a nice way to retrieve the posts based on a website ID. A website can have multiple providers assigned (through website_providers) and providers can have multiple posts assigned to them (also can they provide a custom post_name which should overrule the standard posts.name).
What is the best way to achieve this in Laravel? I've yet tried doing it through relations, but can't get it too work smoothly. I also tried loading the posts using a pretty long join query, but it just doesn't feel right, there's got to be a more simple and prettier way.
Thanks in advance!
1 Answer
1
There is no native relationship for this case.
I created a HasManyThrough
relationship with support for BelongsToMany
: Repository on GitHub
HasManyThrough
BelongsToMany
After the installation you can use it like this:
class Website extends Model
use StaudenmeirEloquentHasManyDeepHasRelationships;
public function posts()
return $this->hasManyDeep(Post::class,
['website_providers', Provider::class, 'provider_posts']);
You can select additional columns like this:
$website->posts()->select('posts.*', 'provider_posts.post_name')->get();
$website->posts()->get(['posts.*', 'provider_posts.post_name']);
There's no
wherePivot()
method (yet). I added an alternative solution to my answer.– Jonas Staudenmeir
Aug 21 at 18:43
wherePivot()
Awesome Jonas, works like a charm. Thanks a lot for your help!
– user2191227
Aug 21 at 18:48
[I meant
withPivot()
.]– Jonas Staudenmeir
Aug 21 at 18:51
withPivot()
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Hi Jonas, thank you! This seems to be working (almost) perfect! One question, any possibility to enrich the posts with the extra column from the pivot table? (In this case the provider_posts > post_name)
– user2191227
Aug 21 at 18:20