Created
July 31, 2020 20:06
-
-
Save kmuenkel/a74c12519d509e9813d9282417f079d6 to your computer and use it in GitHub Desktop.
Eloquent support for a two-way polymorphic pivot table
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AppServiceProvider | |
{ | |
/** | |
* @void | |
*/ | |
protected function boot() | |
{ | |
Relation::macro('setMorphTables', function ($foreignPivotTypeField, $relatedPivotTypeField = null) { | |
/** @var MorphToMany $this */ | |
$parent = $this->getParent(); | |
$this->where($foreignPivotTypeField, $parent->getMorphClass()); | |
if ($relatedPivotTypeField) { | |
$qualifiedTypeField = $this->getTable().'.'.$this->getMorphType(); | |
$this->morphType = $relatedPivotTypeField; | |
/** @var EloquentBuilder $eloquentBuilder */ | |
$eloquentBuilder = $this->getQuery(); | |
$queryBuilder = $eloquentBuilder->getQuery(); | |
//Correct the wheres already created with incorrect assumptions about the pivot field names | |
foreach ($queryBuilder->wheres as $index => $where) { | |
if (isset($where['column']) && $where['column'] === $qualifiedTypeField) { | |
$queryBuilder->wheres[$index]['column'] = $this->getTable().'.'.$relatedPivotTypeField; | |
} | |
} | |
} | |
return $this; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment