MorphMany to MorphTo relation

313 Views Asked by At

I have mangers table and funds table in my laravel project

Managers -> id, name, wallet Funds -> id, amount, fundable_type, fundable_id, receivable_type, receivable_id, status

I have the following relations in Manager model

public function funds()
{
    return $this->morphMany(Fund::class, 'fundable');
}

public function receiveds()
{
    return $this->morphMany(Fund::class, 'receivable');
}

I have the following relations in Fund model


public function fundable()
{
    return $this->morphTo();
}

public function receivable()
{
    return $this->morphTo();
}

$manager->funds is populating fund models well.

I want to receive the managers who received fund a particular manager.

I tried $manager->funds->receivable but it is not working.

2

There are 2 best solutions below

1
Anibal E. Alvarez Sifontes On

In relations specifications you can append the other model's relations:

public function funds()
{
    return $this->morphMany(Fund::class, 'fundable')->with('receivable');
}
0
Raja Durai On

Okay, I was able to get the answer myself.

public function managers()
{
    return $this->hasManyThrough(Manager::class, Fund::class, 'fundable_id', 'id', 'id', 'receivable_id')
->where('fundable_type', Manager::class)->where('receivable_type', Manager::class)->distinct();
}