diff --git a/src/SingleInheritanceBuilderTrait.php b/src/SingleInheritanceBuilderTrait.php new file mode 100644 index 0000000..dbb6f4f --- /dev/null +++ b/src/SingleInheritanceBuilderTrait.php @@ -0,0 +1,52 @@ +$property; + return new $className(); + } + + /** + * This makes it so that polymorphic collections can be constructed properly. + * + * @param array|string $columns + * @return Model[]|static[] + */ + public function getModels($columns = ['*']) + { + /* + * The problem stems from Laravel using the first element in the collection to hydrate the rest of the records + * into Eloquent models. Thus, if any of the subsequent records do is of a type that does not inherit + * from that of the first element, then it fails. + * + * If we use an instance of the root model of the + * inheritance tree, then we can properly hydrate records into polymorphic models. + */ + $rootModel = $this->newSingleInheritanceRootModel(); + return $rootModel->hydrate( + $this->query->get($columns)->all() + )->all(); + } +} diff --git a/tests/Fixtures/Vehicle.php b/tests/Fixtures/Vehicle.php index eff9c91..f223a90 100644 --- a/tests/Fixtures/Vehicle.php +++ b/tests/Fixtures/Vehicle.php @@ -66,4 +66,9 @@ public function setPrimaryKey($primaryKey) { public function setTable($table) { $this->table = $table; } -} \ No newline at end of file + + public function newEloquentBuilder($query) + { + return new VehicleBuilder($query); + } +} diff --git a/tests/Fixtures/VehicleBuilder.php b/tests/Fixtures/VehicleBuilder.php new file mode 100644 index 0000000..0f3c0db --- /dev/null +++ b/tests/Fixtures/VehicleBuilder.php @@ -0,0 +1,13 @@ +save(); + (new Car())->save(); + (new Truck())->save(); + (new Truck())->save(); + (new Bike())->save(); + + $results = Vehicle::all(); + + $this->assertEquals(5, count($results)); + + $this->assertInstanceOf('Nanigans\SingleTableInheritance\Tests\Fixtures\MotorVehicle', $results[0]); + $this->assertInstanceOf('Nanigans\SingleTableInheritance\Tests\Fixtures\Car', $results[1]); + $this->assertInstanceOf('Nanigans\SingleTableInheritance\Tests\Fixtures\Truck', $results[2]); + $this->assertInstanceOf('Nanigans\SingleTableInheritance\Tests\Fixtures\Truck', $results[3]); + $this->assertInstanceOf('Nanigans\SingleTableInheritance\Tests\Fixtures\Bike', $results[4]); + + $results = $results->fresh(); + + $this->assertInstanceOf('Nanigans\SingleTableInheritance\Tests\Fixtures\MotorVehicle', $results[0]); + $this->assertInstanceOf('Nanigans\SingleTableInheritance\Tests\Fixtures\Car', $results[1]); + $this->assertInstanceOf('Nanigans\SingleTableInheritance\Tests\Fixtures\Truck', $results[2]); + $this->assertInstanceOf('Nanigans\SingleTableInheritance\Tests\Fixtures\Truck', $results[3]); + $this->assertInstanceOf('Nanigans\SingleTableInheritance\Tests\Fixtures\Bike', $results[4]); + } +}