Count Related Models On Polymorphic Relationship In Laravel

admin_img Posted By Bajarangi soft , Posted On 10-09-2020

A polymorphic relationship allows the target model to belong to more than one type of model using a single association.Many-to-many polymorphic relations are slightly more complicated than morphOne and morphMany relationships.If you would like to eager load a morphTo relationship, as well as nested relationship counts on the various entities that may be returned by that relationship so today we are going to discuss Count Related Models On Polymorphic Relationship In Laravel

Count Related Models On Polymorphic Relationship In Laravel

Count Related Models On Polymorphic Relationship

use the with method in combination with the morphTo relationship's morphWithCount method.

What is MorphTo method?
"MorphTo" is used to define the relationship from a one-to-one or one-to-many polymorphic table to whichever model or models

 

To learn about "Many To Many Polymorphic Relationships" in laravel visit our  Bajarangisoft site.
 

If you would like to eager load a morphTo relationship, as well as nested relationship counts on the various entities that may be returned by that relationship, you may use the with method in combination with the morphTo rela tionship's morphWithCount  method.
 

In this example, let's assume Video and Post models may create ActivityFeed models. Additionally, let's assume that Video models are associated with Tag models, and Post models are associated with Comment models.
 

Using these model definitions and relationships, we may retrieve ActivityFeed model instances and eager load all parentable models and their respective nested relationship counts:

use Illuminate\Database\Eloquent\Relations\MorphTo;

        $activities = ActivityFeed::query()
                ->with(['parentable' => function (MorphTo $morphTo) {
                    $morphTo->morphWithCount([
                        'App\Photo' => ['tags'],
                        'App\Post' => ['comments'],
                     ]);
        }])->get();

In addition, you may use the loadMorphCount method to eager load all nested relationship counts on the various entities of the polymorphic relation if the ActivityFeed models have already been retrieved:

$activities = ActivityFeed::with('parentable')
->get()
->loadMorphCount('parentable', [
        'App\Video' => ['tags'],
        'App\Post' => ['comments'],
]);

Related Post