Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace App\Traits;
- use Illuminate\Database\Eloquent\Relations\Relation;
- trait HasManyThroughable
- {
- /**
- * This trait allows for a HasMany relationship through a polymorphic intermediate relationship.
- *
- * @param string $related The related class
- * @param string $through The intermediate class
- * @param string $morphName The name of the morphed entity
- * @param null|string $relationship The intermediate relationship
- * @param null|string $morphId
- * @param null|string $morphType
- * @param null|string $morphTypeMap
- *
- * @return mixed
- */
- public function hasManyThroughable($related, $through, $morphName, $relationship = null, $morphId = null, $morphType = null, $morphTypeMap = null)
- {
- $through = new $through();
- $morphId = $morphId ?: $morphName . '_id';
- $morphType = $morphType ?: $morphName . '_type';
- if ($morphTypeMap === null) {
- if (! $morphTypeMap = array_search(get_class($through), Relation::morphMap(), false)) {
- $morphTypeMap = get_class($through);
- }
- }
- $relationship = $relationship ?: camel_case(str_plural(class_basename($through)));
- $throughIds = $this->$relationship->pluck($through->getKeyName());
- return $related::where($morphType, $morphTypeMap)->whereIn($morphId, $throughIds)->get();
- }
- }
Add Comment
Please, Sign In to add comment