简体   繁体   中英

Eloquent activityfeed - shared polymorphic relation

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM