Skip to content

Commit

Permalink
fix(pivot): only use unique classes in the pivot union (Fixes barryvd…
Browse files Browse the repository at this point in the history
  • Loading branch information
pataar committed Oct 28, 2024
1 parent 75b05a9 commit 970a10a
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/Console/ModelsCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -729,8 +729,13 @@ public function getPropertiesFromMethods($model)
$pivot = $this->getClassNameInDestinationFile($model, $pivot);

if ($existingPivot = ($this->properties[$relationObj->getPivotAccessor()] ?? null)) {
// If the pivot is already set, we need to append the type to it
$pivot .= '|' . $existingPivot['type'];
if(!str_contains($existingPivot['type'], $pivot . '|')) {
// If the pivot is already set, we need to append the type to it
$pivot .= '|' . $existingPivot['type'];
} else {
// this class is already set
$pivot = $existingPivot['type'];
}
} else {
// pivots are not always set
$pivot .= '|null';
Expand Down
6 changes: 6 additions & 0 deletions tests/Console/ModelsCommand/Pivot/Models/ModelWithPivot.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,12 @@ public function relationCustomPivotUsingSameAccessor()
->using(CustomPivot::class);
}

public function relationCustomPivotUsingSameAccessorAndClass()
{
return $this->belongsToMany(ModelwithPivot::class)
->using(CustomPivot::class);
}

public function relationWithDifferentCustomPivotUsingSameAccessor()
{
return $this->belongsToMany(ModelwithPivot::class)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
* @property-read DifferentCustomPivot|CustomPivot|null $pivot
* @property-read \Illuminate\Database\Eloquent\Collection<int, ModelWithPivot> $relationCustomPivotUsingSameAccessor
* @property-read int|null $relation_custom_pivot_using_same_accessor_count
* @property-read \Illuminate\Database\Eloquent\Collection<int, ModelWithPivot> $relationCustomPivotUsingSameAccessorAndClass
* @property-read int|null $relation_custom_pivot_using_same_accessor_and_class_count
* @property-read CustomPivot|null $customAccessor
* @property-read \Illuminate\Database\Eloquent\Collection<int, ModelWithPivot> $relationWithCustomPivot
* @property-read int|null $relation_with_custom_pivot_count
Expand Down Expand Up @@ -52,6 +54,12 @@ public function relationCustomPivotUsingSameAccessor()
->using(CustomPivot::class);
}

public function relationCustomPivotUsingSameAccessorAndClass()
{
return $this->belongsToMany(ModelwithPivot::class)
->using(CustomPivot::class);
}

public function relationWithDifferentCustomPivotUsingSameAccessor()
{
return $this->belongsToMany(ModelwithPivot::class)
Expand Down

0 comments on commit 970a10a

Please # to comment.