dorqa95's avatar
Level 12

morphMany through hasMany relations

Hello!

In my project I have Project which hasMany ServicesA and ServicesB and these services has morphMany Metrics. So basicly I would like get the Metrics for the projects through multiple models (ServicesA, ServicesB). What is the proper way to get all off the metrics for specific projects?

These are my models:

class Project extends Model
{
    public function serviceA()
    {
        return $this->hasMany(ServiceA::class);
    }

    public function serviceB()
    {
        return $this->hasMany(ServiceB::class);
    }

    public function metrics()
    {
        // ???
    }
}

class ServiceA extends Model
{
    public function project()
    {
        return $this->belongsTo(Project::class);
    }

    public function metrics()
    {
        return $this->morphMany(Metric::class, 'servicable');
    }
}
class ServiceB extends Model
{
    public function project()
    {
        return $this->belongsTo(Project::class);
    }

    public function metrics()
    {
        return $this->morphMany(Metric::class, 'servicable');
    }
}

class Metric extends Model
{
    public function monitor()
    {
        return $this->morphTo('servicable');
    }
}
0 likes
2 replies
hoyotech's avatar
hoyotech
Best Answer
Level 16

This will return a collection of metrics that are morphed to ServiceA or ServiceB AND belong to the current project model

public function metrics()
    {
        return Metric::query()
            ->whereHasMorph('monitor', [ServiceA::class, ServiceB::class], function (Builder $query) {
                $query->where('project_id', $this->getKey());
            })->get();
    }
1 like

Please or to participate in this conversation.