laravel-json-api / eloquent

Serialize Eloquent models to JSON API resources
MIT License
12 stars 15 forks source link

Duplicates filter in EagerLoadIterator removes valid paths #39

Open tantchen opened 1 month ago

tantchen commented 1 month ago

At this point i have ["station","aircraft","aircraftConfig","person","owner"] in $values because aircraft starts with aircraftConfig the reject callback removes aircraft.

The expected output should be ["aircraft","aircraftConfig","owner","person","station"] but it is ["aircraftConfig","owner","person","station"] with the result that every aircraft will be fetched with a singe select.

https://github.com/laravel-json-api/eloquent/blob/98bbec0b9366e5b06dab6d0710d6e0ff9b9f5f2c/src/QueryBuilder/EagerLoading/EagerLoadIterator.php#L76

tantchen commented 1 month ago

May be a possible fix ...


   /**
     * Get the paths as a collection.
     *
     * Before returning the paths, we filter out any duplicates. For example, if the iterator
     * yields `user` and `user.country`, we only want `user.country` to be in the collection.
     *
     * @return Collection
     */
    public function collect(): Collection
    {
        $values = collect($this);

        return $values->unique()->reject(
            fn ($path) => $values->contains(fn ($check) => $path !== $check && Str::startsWith($check, $path.'.'))
        )->sort()->values();
    }
lindyhopchris commented 20 hours ago

Thanks for reporting, this definitely is a bug. I've added it to the to-do list to address.