staudenmeir / eloquent-has-many-deep

Laravel Eloquent HasManyThrough relationships with unlimited levels
MIT License
2.67k stars 157 forks source link

Receive Intermediate Models After Query #136

Closed MannikJ closed 3 years ago

MannikJ commented 3 years ago

Hi!

is there a way to get the intermediate models after the query was executed?

I have something like this on my job model:

    public function files()
    {
        return $this->hasManyDeep(File::class, [Task::class, TaskFile::class])
         ->select('files.*')
         ->distinct();
    }

So I would like to know if there is some information about the "context" (eg. Task and TaskFile) that I can retrieve from the returned file models. Like in many to many relations I can get the pivot model like this: $model->manyToManyRelation->first()>pivot

I would like to do something similar and get intermediate models of deep relation (Task, TaskFile).

I saw the deep relation adds a laravel_through_key, but I don't even know what that points to, because there are multiple intermediate tables and it could be any of them.

staudenmeir commented 3 years ago

Can you share the structure/migrations of all four tables?

MannikJ commented 3 years ago

In its most basic form:

jobs -id

tasks -id -job_id

task_files -id -task_id -file_id

files -id

staudenmeir commented 3 years ago

You can get data from intermediate/pivot tables, but that doesn't work with all types of distinct relationships: https://github.com/staudenmeir/eloquent-has-many-deep#intermediate-and-pivot-data

In your case, the issue is that a file can be related to a job through multiple different tasks and task_files paths. Then it's not clear which of them should be returned with the file.

MannikJ commented 3 years ago

Yes, the conflict with distinct is obvious. I forgot to leave it out.

But assume we would leave out the distinct and select addition . Then the relation would return a collection with one instance file model for each "path", correct? Do these instances hold any references to their path?

staudenmeir commented 3 years ago

Then the relation would return a collection with one instance file model for each "path", correct?

Yes.

Do these instances hold any references to their path?

Not by default, but you can retrieve any part of the path with withIntermediate()/withPivot().