1
votes

I have an existing app with a polymorphic relationship setup between the comments and the videos/images table (videos and images can have many comments):

videos table

- id
- title

images table

- id
- url

comments table

- id
- parent_id (video or image primary key)
- parent_type (video or image)

Now my client has requested to add an activityfeed to the app. The feed must pull in all the newly added videos and images ordered by rank with their comments.

I have added an activities table

activities table (new)

-id
-parent_id (video or image primary key)
-parent_type (video or image)
-rank
-metadata 

The metadata column contains some denormalised data to display the feed so i don't have to pull in each and every video or image.

Note: above is a simplyfied version of my app. In reality i have more then only video / image types.

How would i setup Eloquent to fetch all the activities with all the related comments with the least possible queries ? I really really want to prevent to do queries in a foreachloop.

An other database scheme for the activities table is possible.

1
What result do you need for this feed? - Jarek Tkaczyk
What do you mean ? I want to fetch an X amount of activities with their comments - PinkFloyd
I mean, do you really need Eloquent result? - Jarek Tkaczyk
Yeah, i want to use my presenters / repo's / commands etc - PinkFloyd
@PinkFloyd if you didn't solve the problem yet, have a look at polymorphic relations; if you used it properly you can fetch the comments this way Activities::with('parent.comments'). - Walid Ammar

1 Answers

0
votes

You can try something like this:

class Activity extends Eloquent {

    function parent() {
        return $this->belongsTo($this->getParentEloquentClass(), 'parent_id');
    }

    private function getParentEloquentClass() {
        switch ($this->parent_type) {
            case 'video':
                return 'Video'; // or your video model class name
            case 'image':
                return 'Image'; // or your image model class name
            ....
        }
    }
}

class Video extends Eloquent {
    function activities() {
        return $this->hasMany('Activity', 'activity_id');
    }
}

Then you may be able to query latest activities with comments like you mentioned:

Activity::with('parent.comments');

I'm not sure if this will work, but it worth to give it a try.