Skip to content

Instantly share code, notes, and snippets.

@kmuenkel
Created July 31, 2020 20:06
Show Gist options
  • Save kmuenkel/a74c12519d509e9813d9282417f079d6 to your computer and use it in GitHub Desktop.
Save kmuenkel/a74c12519d509e9813d9282417f079d6 to your computer and use it in GitHub Desktop.
Eloquent support for a two-way polymorphic pivot table
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