staudenmeir / belongs-to-through

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

BelongsToThrough a polymorphic relationship? #93

Closed nadirabbas closed 10 months ago

nadirabbas commented 10 months ago

Awesome package @staudenmeir! I need a little help if it is not too much to ask I have the following db schema:

image

I want to be able to retrieve the customer on the Task model, which is either directly related to the task, or related through a device, or related through an attachment->device. How can I achieve this using BelongsToThrough package?

staudenmeir commented 10 months ago

Hi @nadirabbas, It's not possible to define this kind of relationship with the package and I don't see any other way to do that either.

nadirabbas commented 10 months ago

@staudenmeir This is working for me, but it does iterate through every record so there seems to be no point anyway. But I still needed to do it to enable customer search on the tasks page:

public function customer()
    {
        if ($this->taskable_type === Customer::class) return $this->belongsTo(Customer::class, 'taskable_id');
        if ($this->taskable_type === Device::class) {
            return $this->belongsToThrough(Customer::class, Device::class, foreignKeyLookup: [
                Device::class => 'taskable_id'
            ]);
        }
        return $this->belongsToThrough(Customer::class, [Device::class, Replaceable::class], foreignKeyLookup: [
            Replaceable::class => 'taskable_id'
        ]);
    }
staudenmeir commented 10 months ago

Yeah, you can get the customer for a single task with such a "dynamic" relationship, but there is no solution for eager loading etc.