single-table-inheritance icon indicating copy to clipboard operation
single-table-inheritance copied to clipboard

Fix: Unable to refresh a collection containing mixed types

Open bezhermoso opened this issue 2 years ago • 1 comments

Ran into an issue when trying to refresh an Eloquent collection that contains a mixture of types. The original implementation uses the first element of the collection to hydrate the rest of the records' array into fresh models, and unfortunately that means that will fail eventually.

This is the result of a failing test I wrote to illustrate this:

1) Nanigans\SingleTableInheritance\Tests\SingleTableInheritanceTraitCollectionTest::testRefresh
Nanigans\SingleTableInheritance\Exceptions\SingleTableInheritanceException: Cannot construct newFromBuilder for unrecognized type=bike

/Users/bezalel/Development/single-table-inheritance/src/SingleTableInheritanceTrait.php:195
/Users/bezalel/Development/single-table-inheritance/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:363
/Users/bezalel/Development/single-table-inheritance/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:362
/Users/bezalel/Development/single-table-inheritance/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:23
/Users/bezalel/Development/single-table-inheritance/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:2132
/Users/bezalel/Development/single-table-inheritance/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:625
/Users/bezalel/Development/single-table-inheritance/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:609
/Users/bezalel/Development/single-table-inheritance/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Collection.php:391
/Users/bezalel/Development/single-table-inheritance/tests/SingleTableInheritanceTraitCollectionTest.php:41

I propose introducing this trait that can be used in a custom Eloquent builder attached to models that use single-table inheritance. See what's done in the Vehicle model fixture and the VehicleBuilder class.

bezhermoso avatar Mar 31 '22 16:03 bezhermoso

Hi @jonspalmer, was hoping you can take a look at this when you get the chance?

bezhermoso avatar May 05 '22 19:05 bezhermoso