skip to Main Content

I have the following models:

Post, Postable, Banner, Poll, Options and Votes.

The relations are as follow:

1 Post can have Many Postables
1 Postable can have either a banner or a poll (Polymorphic relationship)
1 Poll can have many answers
1 Answer can have many votes.

I would like to be able to load the contents of the postables and if the postable is poll, I would like to get the options and the votes on it.

I have tried to implement the following function using the following query

Post::with(['postables' => function ($query) {
                $query->with('postable.options.votes')
                      ->where('postable_type', 'poll');
            }, 'postables' => function ($query) {
                $query->where('postable_type', 'banner')->with('postable');
            }])->get()

I ony get the postables whose type is banner, how can i get the options and the votes as well as the banner in the same call

2

Answers


  1. Chosen as BEST ANSWER

    Since i needed to get the votes and the options with the poll every time, I went with the following solution.

    public class Poll {
    
    protected $with=['options.votes'];
    
    ...
    
    }
    

  2. You can consider doing like below:

    use IlluminateDatabaseEloquentRelationsMorphTo;
    
    Post::with(['postables' => function (MorphTo $morphTo) {
            $morphTo->morphWith([
                Poll::class => ['options.votes'],
            ]);
        }])->get();
    

    Conference https://laravel.com/docs/10.x/eloquent-relationships#nested-eager-loading-morphto-relationships

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search