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']);





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





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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)