staudenmeir / belongs-to-through

Laravel Eloquent BelongsToThrough relationships
MIT License
1.15k stars 88 forks source link

User → belongs to → A or B → morph to many → C #65

Closed Vicftz closed 2 years ago

Vicftz commented 2 years ago

Hi,

I tried to solve this to recover C model, through a belongsTo relation to A (or B), like this : User → belongs to → A or B → morph to many → C I tried many options but unfornatly unsuccessfully. If someone has an idea, I'll super gratefull. Thanks in advance

staudenmeir commented 2 years ago

Do you want to retrieve a single related model or all related ones?

Vicftz commented 2 years ago

Hi @staudenmeir, All related one (if possible of course)!

staudenmeir commented 2 years ago

Use one of my other packages instead: https://github.com/staudenmeir/eloquent-has-many-deep

Replace taggables, taggable_type and taggable_id with your MorphToMany table and column names (and B, C, b_id & c_id, of course):

class User extends Model
{
    use \Staudenmeir\EloquentHasManyDeep\HasRelationships;

    public function cs()
    {
        return $this->hasManyDeep(
            C::class,
            [B::class, 'taggables'],
            ['id', ['taggable_type', 'taggable_id'], 'id'],
            ['b_id', null, 'c_id']
        );
    }
}
Vicftz commented 2 years ago

It works ! Thank you so much ! And do you know if it's possible to recover C through A in the same time ?

staudenmeir commented 2 years ago

This is a bit more complicated and requires an additional package: https://github.com/staudenmeir/laravel-merged-relations

Define a second relationship like cs with B instead of A. Then you can merge them as described in the README:

Schema::createMergeView(
    'all_cs',
    [(new User)->csThroughA(), (new User)->csThroughB()]
);

class User extends Model
{
    use \Staudenmeir\LaravelMergedRelations\Eloquent\HasMergedRelationships;

    public function allCs()
    {
        return $this->mergedRelationWithModel(C::class, 'all_cs');
    }
}