8889841cMorphTo.php000066600000025453150515304400006657 0ustar00morphType = $type; parent::__construct($query, $parent, $foreignKey, $ownerKey, $relation); } /** * Set the constraints for an eager load of the relation. * * @param array $models * @return void */ public function addEagerConstraints(array $models) { $this->buildDictionary($this->models = Collection::make($models)); } /** * Build a dictionary with the models. * * @param \Illuminate\Database\Eloquent\Collection $models * @return void */ protected function buildDictionary(Collection $models) { foreach ($models as $model) { if ($model->{$this->morphType}) { $morphTypeKey = $this->getDictionaryKey($model->{$this->morphType}); $foreignKeyKey = $this->getDictionaryKey($model->{$this->foreignKey}); $this->dictionary[$morphTypeKey][$foreignKeyKey][] = $model; } } } /** * Get the results of the relationship. * * Called via eager load method of Eloquent query builder. * * @return mixed */ public function getEager() { foreach (array_keys($this->dictionary) as $type) { $this->matchToMorphParents($type, $this->getResultsByType($type)); } return $this->models; } /** * Get all of the relation results for a type. * * @param string $type * @return \Illuminate\Database\Eloquent\Collection */ protected function getResultsByType($type) { $instance = $this->createModelByType($type); $ownerKey = $this->ownerKey ?? $instance->getKeyName(); $query = $this->replayMacros($instance->newQuery()) ->mergeConstraintsFrom($this->getQuery()) ->with(array_merge( $this->getQuery()->getEagerLoads(), (array) ($this->morphableEagerLoads[get_class($instance)] ?? []) )) ->withCount( (array) ($this->morphableEagerLoadCounts[get_class($instance)] ?? []) ); if ($callback = ($this->morphableConstraints[get_class($instance)] ?? null)) { $callback($query); } $whereIn = $this->whereInMethod($instance, $ownerKey); return $query->{$whereIn}( $instance->getTable().'.'.$ownerKey, $this->gatherKeysByType($type, $instance->getKeyType()) )->get(); } /** * Gather all of the foreign keys for a given type. * * @param string $type * @param string $keyType * @return array */ protected function gatherKeysByType($type, $keyType) { return $keyType !== 'string' ? array_keys($this->dictionary[$type]) : array_map(function ($modelId) { return (string) $modelId; }, array_filter(array_keys($this->dictionary[$type]))); } /** * Create a new model instance by type. * * @param string $type * @return \Illuminate\Database\Eloquent\Model */ public function createModelByType($type) { $class = Model::getActualClassNameForMorph($type); return tap(new $class, function ($instance) { if (! $instance->getConnectionName()) { $instance->setConnection($this->getConnection()->getName()); } }); } /** * Match the eagerly loaded results to their parents. * * @param array $models * @param \Illuminate\Database\Eloquent\Collection $results * @param string $relation * @return array */ public function match(array $models, Collection $results, $relation) { return $models; } /** * Match the results for a given type to their parents. * * @param string $type * @param \Illuminate\Database\Eloquent\Collection $results * @return void */ protected function matchToMorphParents($type, Collection $results) { foreach ($results as $result) { $ownerKey = ! is_null($this->ownerKey) ? $this->getDictionaryKey($result->{$this->ownerKey}) : $result->getKey(); if (isset($this->dictionary[$type][$ownerKey])) { foreach ($this->dictionary[$type][$ownerKey] as $model) { $model->setRelation($this->relationName, $result); } } } } /** * Associate the model instance to the given parent. * * @param \Illuminate\Database\Eloquent\Model $model * @return \Illuminate\Database\Eloquent\Model */ public function associate($model) { if ($model instanceof Model) { $foreignKey = $this->ownerKey && $model->{$this->ownerKey} ? $this->ownerKey : $model->getKeyName(); } $this->parent->setAttribute( $this->foreignKey, $model instanceof Model ? $model->{$foreignKey} : null ); $this->parent->setAttribute( $this->morphType, $model instanceof Model ? $model->getMorphClass() : null ); return $this->parent->setRelation($this->relationName, $model); } /** * Dissociate previously associated model from the given parent. * * @return \Illuminate\Database\Eloquent\Model */ public function dissociate() { $this->parent->setAttribute($this->foreignKey, null); $this->parent->setAttribute($this->morphType, null); return $this->parent->setRelation($this->relationName, null); } /** * Touch all of the related models for the relationship. * * @return void */ public function touch() { if (! is_null($this->child->{$this->foreignKey})) { parent::touch(); } } /** * Make a new related instance for the given model. * * @param \Illuminate\Database\Eloquent\Model $parent * @return \Illuminate\Database\Eloquent\Model */ protected function newRelatedInstanceFor(Model $parent) { return $parent->{$this->getRelationName()}()->getRelated()->newInstance(); } /** * Get the foreign key "type" name. * * @return string */ public function getMorphType() { return $this->morphType; } /** * Get the dictionary used by the relationship. * * @return array */ public function getDictionary() { return $this->dictionary; } /** * Specify which relations to load for a given morph type. * * @param array $with * @return \Illuminate\Database\Eloquent\Relations\MorphTo */ public function morphWith(array $with) { $this->morphableEagerLoads = array_merge( $this->morphableEagerLoads, $with ); return $this; } /** * Specify which relationship counts to load for a given morph type. * * @param array $withCount * @return \Illuminate\Database\Eloquent\Relations\MorphTo */ public function morphWithCount(array $withCount) { $this->morphableEagerLoadCounts = array_merge( $this->morphableEagerLoadCounts, $withCount ); return $this; } /** * Specify constraints on the query for a given morph type. * * @param array $callbacks * @return \Illuminate\Database\Eloquent\Relations\MorphTo */ public function constrain(array $callbacks) { $this->morphableConstraints = array_merge( $this->morphableConstraints, $callbacks ); return $this; } /** * Replay stored macro calls on the actual related instance. * * @param \Illuminate\Database\Eloquent\Builder $query * @return \Illuminate\Database\Eloquent\Builder */ protected function replayMacros(Builder $query) { foreach ($this->macroBuffer as $macro) { $query->{$macro['method']}(...$macro['parameters']); } return $query; } /** * Handle dynamic method calls to the relationship. * * @param string $method * @param array $parameters * @return mixed */ public function __call($method, $parameters) { try { $result = parent::__call($method, $parameters); if (in_array($method, ['select', 'selectRaw', 'selectSub', 'addSelect', 'withoutGlobalScopes'])) { $this->macroBuffer[] = compact('method', 'parameters'); } return $result; } // If we tried to call a method that does not exist on the parent Builder instance, // we'll assume that we want to call a query macro (e.g. withTrashed) that only // exists on related models. We will just store the call and replay it later. catch (BadMethodCallException $e) { $this->macroBuffer[] = compact('method', 'parameters'); return $this; } } } HasOne.php000066600000010061150515304400006431 0ustar00getParentKey())) { return $this->getDefaultFor($this->parent); } return $this->query->first() ?: $this->getDefaultFor($this->parent); } /** * Initialize the relation on a set of models. * * @param array $models * @param string $relation * @return array */ public function initRelation(array $models, $relation) { foreach ($models as $model) { $model->setRelation($relation, $this->getDefaultFor($model)); } return $models; } /** * Match the eagerly loaded results to their parents. * * @param array $models * @param \Illuminate\Database\Eloquent\Collection $results * @param string $relation * @return array */ public function match(array $models, Collection $results, $relation) { return $this->matchOne($models, $results, $relation); } /** * Add the constraints for an internal relationship existence query. * * Essentially, these queries compare on column names like "whereColumn". * * @param \Illuminate\Database\Eloquent\Builder $query * @param \Illuminate\Database\Eloquent\Builder $parentQuery * @param array|mixed $columns * @return \Illuminate\Database\Eloquent\Builder */ public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*']) { if ($this->isOneOfMany()) { $this->mergeOneOfManyJoinsTo($query); } return parent::getRelationExistenceQuery($query, $parentQuery, $columns); } /** * Add constraints for inner join subselect for one of many relationships. * * @param \Illuminate\Database\Eloquent\Builder $query * @param string|null $column * @param string|null $aggregate * @return void */ public function addOneOfManySubQueryConstraints(Builder $query, $column = null, $aggregate = null) { $query->addSelect($this->foreignKey); } /** * Get the columns that should be selected by the one of many subquery. * * @return array|string */ public function getOneOfManySubQuerySelectColumns() { return $this->foreignKey; } /** * Add join query constraints for one of many relationships. * * @param \Illuminate\Database\Eloquent\JoinClause $join * @return void */ public function addOneOfManyJoinSubQueryConstraints(JoinClause $join) { $join->on($this->qualifySubSelectColumn($this->foreignKey), '=', $this->qualifyRelatedColumn($this->foreignKey)); } /** * Make a new related instance for the given model. * * @param \Illuminate\Database\Eloquent\Model $parent * @return \Illuminate\Database\Eloquent\Model */ public function newRelatedInstanceFor(Model $parent) { return $this->related->newInstance()->setAttribute( $this->getForeignKeyName(), $parent->{$this->localKey} ); } /** * Get the value of the model's foreign key. * * @param \Illuminate\Database\Eloquent\Model $model * @return mixed */ protected function getRelatedKeyFrom(Model $model) { return $model->getAttribute($this->getForeignKeyName()); } } HasManyThrough.php000066600000050505150515304400010164 0ustar00localKey = $localKey; $this->firstKey = $firstKey; $this->secondKey = $secondKey; $this->farParent = $farParent; $this->throughParent = $throughParent; $this->secondLocalKey = $secondLocalKey; parent::__construct($query, $throughParent); } /** * Set the base constraints on the relation query. * * @return void */ public function addConstraints() { $localValue = $this->farParent[$this->localKey]; $this->performJoin(); if (static::$constraints) { $this->query->where($this->getQualifiedFirstKeyName(), '=', $localValue); } } /** * Set the join clause on the query. * * @param \Illuminate\Database\Eloquent\Builder|null $query * @return void */ protected function performJoin(Builder $query = null) { $query = $query ?: $this->query; $farKey = $this->getQualifiedFarKeyName(); $query->join($this->throughParent->getTable(), $this->getQualifiedParentKeyName(), '=', $farKey); if ($this->throughParentSoftDeletes()) { $query->withGlobalScope('SoftDeletableHasManyThrough', function ($query) { $query->whereNull($this->throughParent->getQualifiedDeletedAtColumn()); }); } } /** * Get the fully qualified parent key name. * * @return string */ public function getQualifiedParentKeyName() { return $this->parent->qualifyColumn($this->secondLocalKey); } /** * Determine whether "through" parent of the relation uses Soft Deletes. * * @return bool */ public function throughParentSoftDeletes() { return in_array(SoftDeletes::class, class_uses_recursive($this->throughParent)); } /** * Indicate that trashed "through" parents should be included in the query. * * @return $this */ public function withTrashedParents() { $this->query->withoutGlobalScope('SoftDeletableHasManyThrough'); return $this; } /** * Set the constraints for an eager load of the relation. * * @param array $models * @return void */ public function addEagerConstraints(array $models) { $whereIn = $this->whereInMethod($this->farParent, $this->localKey); $this->query->{$whereIn}( $this->getQualifiedFirstKeyName(), $this->getKeys($models, $this->localKey) ); } /** * Initialize the relation on a set of models. * * @param array $models * @param string $relation * @return array */ public function initRelation(array $models, $relation) { foreach ($models as $model) { $model->setRelation($relation, $this->related->newCollection()); } return $models; } /** * Match the eagerly loaded results to their parents. * * @param array $models * @param \Illuminate\Database\Eloquent\Collection $results * @param string $relation * @return array */ public function match(array $models, Collection $results, $relation) { $dictionary = $this->buildDictionary($results); // Once we have the dictionary we can simply spin through the parent models to // link them up with their children using the keyed dictionary to make the // matching very convenient and easy work. Then we'll just return them. foreach ($models as $model) { if (isset($dictionary[$key = $this->getDictionaryKey($model->getAttribute($this->localKey))])) { $model->setRelation( $relation, $this->related->newCollection($dictionary[$key]) ); } } return $models; } /** * Build model dictionary keyed by the relation's foreign key. * * @param \Illuminate\Database\Eloquent\Collection $results * @return array */ protected function buildDictionary(Collection $results) { $dictionary = []; // First we will create a dictionary of models keyed by the foreign key of the // relationship as this will allow us to quickly access all of the related // models without having to do nested looping which will be quite slow. foreach ($results as $result) { $dictionary[$result->laravel_through_key][] = $result; } return $dictionary; } /** * Get the first related model record matching the attributes or instantiate it. * * @param array $attributes * @return \Illuminate\Database\Eloquent\Model */ public function firstOrNew(array $attributes) { if (is_null($instance = $this->where($attributes)->first())) { $instance = $this->related->newInstance($attributes); } return $instance; } /** * Create or update a related record matching the attributes, and fill it with values. * * @param array $attributes * @param array $values * @return \Illuminate\Database\Eloquent\Model */ public function updateOrCreate(array $attributes, array $values = []) { $instance = $this->firstOrNew($attributes); $instance->fill($values)->save(); return $instance; } /** * Add a basic where clause to the query, and return the first result. * * @param \Closure|string|array $column * @param mixed $operator * @param mixed $value * @param string $boolean * @return \Illuminate\Database\Eloquent\Model|static */ public function firstWhere($column, $operator = null, $value = null, $boolean = 'and') { return $this->where($column, $operator, $value, $boolean)->first(); } /** * Execute the query and get the first related model. * * @param array $columns * @return mixed */ public function first($columns = ['*']) { $results = $this->take(1)->get($columns); return count($results) > 0 ? $results->first() : null; } /** * Execute the query and get the first result or throw an exception. * * @param array $columns * @return \Illuminate\Database\Eloquent\Model|static * * @throws \Illuminate\Database\Eloquent\ModelNotFoundException */ public function firstOrFail($columns = ['*']) { if (! is_null($model = $this->first($columns))) { return $model; } throw (new ModelNotFoundException)->setModel(get_class($this->related)); } /** * Find a related model by its primary key. * * @param mixed $id * @param array $columns * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|null */ public function find($id, $columns = ['*']) { if (is_array($id) || $id instanceof Arrayable) { return $this->findMany($id, $columns); } return $this->where( $this->getRelated()->getQualifiedKeyName(), '=', $id )->first($columns); } /** * Find multiple related models by their primary keys. * * @param \Illuminate\Contracts\Support\Arrayable|array $ids * @param array $columns * @return \Illuminate\Database\Eloquent\Collection */ public function findMany($ids, $columns = ['*']) { $ids = $ids instanceof Arrayable ? $ids->toArray() : $ids; if (empty($ids)) { return $this->getRelated()->newCollection(); } return $this->whereIn( $this->getRelated()->getQualifiedKeyName(), $ids )->get($columns); } /** * Find a related model by its primary key or throw an exception. * * @param mixed $id * @param array $columns * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection * * @throws \Illuminate\Database\Eloquent\ModelNotFoundException */ public function findOrFail($id, $columns = ['*']) { $result = $this->find($id, $columns); $id = $id instanceof Arrayable ? $id->toArray() : $id; if (is_array($id)) { if (count($result) === count(array_unique($id))) { return $result; } } elseif (! is_null($result)) { return $result; } throw (new ModelNotFoundException)->setModel(get_class($this->related), $id); } /** * Get the results of the relationship. * * @return mixed */ public function getResults() { return ! is_null($this->farParent->{$this->localKey}) ? $this->get() : $this->related->newCollection(); } /** * Execute the query as a "select" statement. * * @param array $columns * @return \Illuminate\Database\Eloquent\Collection */ public function get($columns = ['*']) { $builder = $this->prepareQueryBuilder($columns); $models = $builder->getModels(); // If we actually found models we will also eager load any relationships that // have been specified as needing to be eager loaded. This will solve the // n + 1 query problem for the developer and also increase performance. if (count($models) > 0) { $models = $builder->eagerLoadRelations($models); } return $this->related->newCollection($models); } /** * Get a paginator for the "select" statement. * * @param int|null $perPage * @param array $columns * @param string $pageName * @param int $page * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator */ public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null) { $this->query->addSelect($this->shouldSelect($columns)); return $this->query->paginate($perPage, $columns, $pageName, $page); } /** * Paginate the given query into a simple paginator. * * @param int|null $perPage * @param array $columns * @param string $pageName * @param int|null $page * @return \Illuminate\Contracts\Pagination\Paginator */ public function simplePaginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null) { $this->query->addSelect($this->shouldSelect($columns)); return $this->query->simplePaginate($perPage, $columns, $pageName, $page); } /** * Paginate the given query into a cursor paginator. * * @param int|null $perPage * @param array $columns * @param string $cursorName * @param string|null $cursor * @return \Illuminate\Contracts\Pagination\CursorPaginator */ public function cursorPaginate($perPage = null, $columns = ['*'], $cursorName = 'cursor', $cursor = null) { $this->query->addSelect($this->shouldSelect($columns)); return $this->query->cursorPaginate($perPage, $columns, $cursorName, $cursor); } /** * Set the select clause for the relation query. * * @param array $columns * @return array */ protected function shouldSelect(array $columns = ['*']) { if ($columns == ['*']) { $columns = [$this->related->getTable().'.*']; } return array_merge($columns, [$this->getQualifiedFirstKeyName().' as laravel_through_key']); } /** * Chunk the results of the query. * * @param int $count * @param callable $callback * @return bool */ public function chunk($count, callable $callback) { return $this->prepareQueryBuilder()->chunk($count, $callback); } /** * Chunk the results of a query by comparing numeric IDs. * * @param int $count * @param callable $callback * @param string|null $column * @param string|null $alias * @return bool */ public function chunkById($count, callable $callback, $column = null, $alias = null) { $column = $column ?? $this->getRelated()->getQualifiedKeyName(); $alias = $alias ?? $this->getRelated()->getKeyName(); return $this->prepareQueryBuilder()->chunkById($count, $callback, $column, $alias); } /** * Get a generator for the given query. * * @return \Generator */ public function cursor() { return $this->prepareQueryBuilder()->cursor(); } /** * Execute a callback over each item while chunking. * * @param callable $callback * @param int $count * @return bool */ public function each(callable $callback, $count = 1000) { return $this->chunk($count, function ($results) use ($callback) { foreach ($results as $key => $value) { if ($callback($value, $key) === false) { return false; } } }); } /** * Query lazily, by chunks of the given size. * * @param int $chunkSize * @return \Illuminate\Support\LazyCollection */ public function lazy($chunkSize = 1000) { return $this->prepareQueryBuilder()->lazy($chunkSize); } /** * Query lazily, by chunking the results of a query by comparing IDs. * * @param int $chunkSize * @param string|null $column * @param string|null $alias * @return \Illuminate\Support\LazyCollection */ public function lazyById($chunkSize = 1000, $column = null, $alias = null) { $column = $column ?? $this->getRelated()->getQualifiedKeyName(); $alias = $alias ?? $this->getRelated()->getKeyName(); return $this->prepareQueryBuilder()->lazyById($chunkSize, $column, $alias); } /** * Prepare the query builder for query execution. * * @param array $columns * @return \Illuminate\Database\Eloquent\Builder */ protected function prepareQueryBuilder($columns = ['*']) { $builder = $this->query->applyScopes(); return $builder->addSelect( $this->shouldSelect($builder->getQuery()->columns ? [] : $columns) ); } /** * Add the constraints for a relationship query. * * @param \Illuminate\Database\Eloquent\Builder $query * @param \Illuminate\Database\Eloquent\Builder $parentQuery * @param array|mixed $columns * @return \Illuminate\Database\Eloquent\Builder */ public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*']) { if ($parentQuery->getQuery()->from === $query->getQuery()->from) { return $this->getRelationExistenceQueryForSelfRelation($query, $parentQuery, $columns); } if ($parentQuery->getQuery()->from === $this->throughParent->getTable()) { return $this->getRelationExistenceQueryForThroughSelfRelation($query, $parentQuery, $columns); } $this->performJoin($query); return $query->select($columns)->whereColumn( $this->getQualifiedLocalKeyName(), '=', $this->getQualifiedFirstKeyName() ); } /** * Add the constraints for a relationship query on the same table. * * @param \Illuminate\Database\Eloquent\Builder $query * @param \Illuminate\Database\Eloquent\Builder $parentQuery * @param array|mixed $columns * @return \Illuminate\Database\Eloquent\Builder */ public function getRelationExistenceQueryForSelfRelation(Builder $query, Builder $parentQuery, $columns = ['*']) { $query->from($query->getModel()->getTable().' as '.$hash = $this->getRelationCountHash()); $query->join($this->throughParent->getTable(), $this->getQualifiedParentKeyName(), '=', $hash.'.'.$this->secondKey); if ($this->throughParentSoftDeletes()) { $query->whereNull($this->throughParent->getQualifiedDeletedAtColumn()); } $query->getModel()->setTable($hash); return $query->select($columns)->whereColumn( $parentQuery->getQuery()->from.'.'.$this->localKey, '=', $this->getQualifiedFirstKeyName() ); } /** * Add the constraints for a relationship query on the same table as the through parent. * * @param \Illuminate\Database\Eloquent\Builder $query * @param \Illuminate\Database\Eloquent\Builder $parentQuery * @param array|mixed $columns * @return \Illuminate\Database\Eloquent\Builder */ public function getRelationExistenceQueryForThroughSelfRelation(Builder $query, Builder $parentQuery, $columns = ['*']) { $table = $this->throughParent->getTable().' as '.$hash = $this->getRelationCountHash(); $query->join($table, $hash.'.'.$this->secondLocalKey, '=', $this->getQualifiedFarKeyName()); if ($this->throughParentSoftDeletes()) { $query->whereNull($hash.'.'.$this->throughParent->getDeletedAtColumn()); } return $query->select($columns)->whereColumn( $parentQuery->getQuery()->from.'.'.$this->localKey, '=', $hash.'.'.$this->firstKey ); } /** * Get the qualified foreign key on the related model. * * @return string */ public function getQualifiedFarKeyName() { return $this->getQualifiedForeignKeyName(); } /** * Get the foreign key on the "through" model. * * @return string */ public function getFirstKeyName() { return $this->firstKey; } /** * Get the qualified foreign key on the "through" model. * * @return string */ public function getQualifiedFirstKeyName() { return $this->throughParent->qualifyColumn($this->firstKey); } /** * Get the foreign key on the related model. * * @return string */ public function getForeignKeyName() { return $this->secondKey; } /** * Get the qualified foreign key on the related model. * * @return string */ public function getQualifiedForeignKeyName() { return $this->related->qualifyColumn($this->secondKey); } /** * Get the local key on the far parent model. * * @return string */ public function getLocalKeyName() { return $this->localKey; } /** * Get the qualified local key on the far parent model. * * @return string */ public function getQualifiedLocalKeyName() { return $this->farParent->qualifyColumn($this->localKey); } /** * Get the local key on the intermediary model. * * @return string */ public function getSecondLocalKeyName() { return $this->secondLocalKey; } } Concerns/InteractsWithDictionary.php000066600000001700150515304400013644 0ustar00__toString(); } if (function_exists('enum_exists') && $attribute instanceof BackedEnum) { return $attribute->value; } throw new InvalidArgumentException('Model attribute value is an object but does not have a __toString method.'); } return $attribute; } } Concerns/ComparesRelatedModels.php000066600000004047150515304400013253 0ustar00compareKeys($this->getParentKey(), $this->getRelatedKeyFrom($model)) && $this->related->getTable() === $model->getTable() && $this->related->getConnectionName() === $model->getConnectionName(); if ($match && $this instanceof SupportsPartialRelations && $this->isOneOfMany()) { return $this->query ->whereKey($model->getKey()) ->exists(); } return $match; } /** * Determine if the model is not the related instance of the relationship. * * @param \Illuminate\Database\Eloquent\Model|null $model * @return bool */ public function isNot($model) { return ! $this->is($model); } /** * Get the value of the parent model's key. * * @return mixed */ abstract public function getParentKey(); /** * Get the value of the model's related key. * * @param \Illuminate\Database\Eloquent\Model $model * @return mixed */ abstract protected function getRelatedKeyFrom(Model $model); /** * Compare the parent key with the related key. * * @param mixed $parentKey * @param mixed $relatedKey * @return bool */ protected function compareKeys($parentKey, $relatedKey) { if (empty($parentKey) || empty($relatedKey)) { return false; } if (is_int($parentKey) || is_int($relatedKey)) { return (int) $parentKey === (int) $relatedKey; } return $parentKey === $relatedKey; } } Concerns/InteractsWithPivotTable.php000066600000050543150515304400013621 0ustar00 [], 'detached' => [], ]; $records = $this->formatRecordsList($this->parseIds($ids)); // Next, we will determine which IDs should get removed from the join table by // checking which of the given ID/records is in the list of current records // and removing all of those rows from this "intermediate" joining table. $detach = array_values(array_intersect( $this->newPivotQuery()->pluck($this->relatedPivotKey)->all(), array_keys($records) )); if (count($detach) > 0) { $this->detach($detach, false); $changes['detached'] = $this->castKeys($detach); } // Finally, for all of the records which were not "detached", we'll attach the // records into the intermediate table. Then, we will add those attaches to // this change list and get ready to return these results to the callers. $attach = array_diff_key($records, array_flip($detach)); if (count($attach) > 0) { $this->attach($attach, [], false); $changes['attached'] = array_keys($attach); } // Once we have finished attaching or detaching the records, we will see if we // have done any attaching or detaching, and if we have we will touch these // relationships if they are configured to touch on any database updates. if ($touch && (count($changes['attached']) || count($changes['detached']))) { $this->touchIfTouching(); } return $changes; } /** * Sync the intermediate tables with a list of IDs without detaching. * * @param \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Model|array $ids * @return array */ public function syncWithoutDetaching($ids) { return $this->sync($ids, false); } /** * Sync the intermediate tables with a list of IDs or collection of models. * * @param \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Model|array $ids * @param bool $detaching * @return array */ public function sync($ids, $detaching = true) { $changes = [ 'attached' => [], 'detached' => [], 'updated' => [], ]; // First we need to attach any of the associated models that are not currently // in this joining table. We'll spin through the given IDs, checking to see // if they exist in the array of current ones, and if not we will insert. $current = $this->getCurrentlyAttachedPivots() ->pluck($this->relatedPivotKey)->all(); $detach = array_diff($current, array_keys( $records = $this->formatRecordsList($this->parseIds($ids)) )); // Next, we will take the differences of the currents and given IDs and detach // all of the entities that exist in the "current" array but are not in the // array of the new IDs given to the method which will complete the sync. if ($detaching && count($detach) > 0) { $this->detach($detach); $changes['detached'] = $this->castKeys($detach); } // Now we are finally ready to attach the new records. Note that we'll disable // touching until after the entire operation is complete so we don't fire a // ton of touch operations until we are totally done syncing the records. $changes = array_merge( $changes, $this->attachNew($records, $current, false) ); // Once we have finished attaching or detaching the records, we will see if we // have done any attaching or detaching, and if we have we will touch these // relationships if they are configured to touch on any database updates. if (count($changes['attached']) || count($changes['updated']) || count($changes['detached'])) { $this->touchIfTouching(); } return $changes; } /** * Sync the intermediate tables with a list of IDs or collection of models with the given pivot values. * * @param \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Model|array $ids * @param array $values * @param bool $detaching * @return array */ public function syncWithPivotValues($ids, array $values, bool $detaching = true) { return $this->sync(collect($this->parseIds($ids))->mapWithKeys(function ($id) use ($values) { return [$id => $values]; }), $detaching); } /** * Format the sync / toggle record list so that it is keyed by ID. * * @param array $records * @return array */ protected function formatRecordsList(array $records) { return collect($records)->mapWithKeys(function ($attributes, $id) { if (! is_array($attributes)) { [$id, $attributes] = [$attributes, []]; } return [$id => $attributes]; })->all(); } /** * Attach all of the records that aren't in the given current records. * * @param array $records * @param array $current * @param bool $touch * @return array */ protected function attachNew(array $records, array $current, $touch = true) { $changes = ['attached' => [], 'updated' => []]; foreach ($records as $id => $attributes) { // If the ID is not in the list of existing pivot IDs, we will insert a new pivot // record, otherwise, we will just update this existing record on this joining // table, so that the developers will easily update these records pain free. if (! in_array($id, $current)) { $this->attach($id, $attributes, $touch); $changes['attached'][] = $this->castKey($id); } // Now we'll try to update an existing pivot record with the attributes that were // given to the method. If the model is actually updated we will add it to the // list of updated pivot records so we return them back out to the consumer. elseif (count($attributes) > 0 && $this->updateExistingPivot($id, $attributes, $touch)) { $changes['updated'][] = $this->castKey($id); } } return $changes; } /** * Update an existing pivot record on the table. * * @param mixed $id * @param array $attributes * @param bool $touch * @return int */ public function updateExistingPivot($id, array $attributes, $touch = true) { if ($this->using && empty($this->pivotWheres) && empty($this->pivotWhereIns) && empty($this->pivotWhereNulls)) { return $this->updateExistingPivotUsingCustomClass($id, $attributes, $touch); } if (in_array($this->updatedAt(), $this->pivotColumns)) { $attributes = $this->addTimestampsToAttachment($attributes, true); } $updated = $this->newPivotStatementForId($this->parseId($id))->update( $this->castAttributes($attributes) ); if ($touch) { $this->touchIfTouching(); } return $updated; } /** * Update an existing pivot record on the table via a custom class. * * @param mixed $id * @param array $attributes * @param bool $touch * @return int */ protected function updateExistingPivotUsingCustomClass($id, array $attributes, $touch) { $pivot = $this->getCurrentlyAttachedPivots() ->where($this->foreignPivotKey, $this->parent->{$this->parentKey}) ->where($this->relatedPivotKey, $this->parseId($id)) ->first(); $updated = $pivot ? $pivot->fill($attributes)->isDirty() : false; if ($updated) { $pivot->save(); } if ($touch) { $this->touchIfTouching(); } return (int) $updated; } /** * Attach a model to the parent. * * @param mixed $id * @param array $attributes * @param bool $touch * @return void */ public function attach($id, array $attributes = [], $touch = true) { if ($this->using) { $this->attachUsingCustomClass($id, $attributes); } else { // Here we will insert the attachment records into the pivot table. Once we have // inserted the records, we will touch the relationships if necessary and the // function will return. We can parse the IDs before inserting the records. $this->newPivotStatement()->insert($this->formatAttachRecords( $this->parseIds($id), $attributes )); } if ($touch) { $this->touchIfTouching(); } } /** * Attach a model to the parent using a custom class. * * @param mixed $id * @param array $attributes * @return void */ protected function attachUsingCustomClass($id, array $attributes) { $records = $this->formatAttachRecords( $this->parseIds($id), $attributes ); foreach ($records as $record) { $this->newPivot($record, false)->save(); } } /** * Create an array of records to insert into the pivot table. * * @param array $ids * @param array $attributes * @return array */ protected function formatAttachRecords($ids, array $attributes) { $records = []; $hasTimestamps = ($this->hasPivotColumn($this->createdAt()) || $this->hasPivotColumn($this->updatedAt())); // To create the attachment records, we will simply spin through the IDs given // and create a new record to insert for each ID. Each ID may actually be a // key in the array, with extra attributes to be placed in other columns. foreach ($ids as $key => $value) { $records[] = $this->formatAttachRecord( $key, $value, $attributes, $hasTimestamps ); } return $records; } /** * Create a full attachment record payload. * * @param int $key * @param mixed $value * @param array $attributes * @param bool $hasTimestamps * @return array */ protected function formatAttachRecord($key, $value, $attributes, $hasTimestamps) { [$id, $attributes] = $this->extractAttachIdAndAttributes($key, $value, $attributes); return array_merge( $this->baseAttachRecord($id, $hasTimestamps), $this->castAttributes($attributes) ); } /** * Get the attach record ID and extra attributes. * * @param mixed $key * @param mixed $value * @param array $attributes * @return array */ protected function extractAttachIdAndAttributes($key, $value, array $attributes) { return is_array($value) ? [$key, array_merge($value, $attributes)] : [$value, $attributes]; } /** * Create a new pivot attachment record. * * @param int $id * @param bool $timed * @return array */ protected function baseAttachRecord($id, $timed) { $record[$this->relatedPivotKey] = $id; $record[$this->foreignPivotKey] = $this->parent->{$this->parentKey}; // If the record needs to have creation and update timestamps, we will make // them by calling the parent model's "freshTimestamp" method which will // provide us with a fresh timestamp in this model's preferred format. if ($timed) { $record = $this->addTimestampsToAttachment($record); } foreach ($this->pivotValues as $value) { $record[$value['column']] = $value['value']; } return $record; } /** * Set the creation and update timestamps on an attach record. * * @param array $record * @param bool $exists * @return array */ protected function addTimestampsToAttachment(array $record, $exists = false) { $fresh = $this->parent->freshTimestamp(); if ($this->using) { $pivotModel = new $this->using; $fresh = $fresh->format($pivotModel->getDateFormat()); } if (! $exists && $this->hasPivotColumn($this->createdAt())) { $record[$this->createdAt()] = $fresh; } if ($this->hasPivotColumn($this->updatedAt())) { $record[$this->updatedAt()] = $fresh; } return $record; } /** * Determine whether the given column is defined as a pivot column. * * @param string $column * @return bool */ public function hasPivotColumn($column) { return in_array($column, $this->pivotColumns); } /** * Detach models from the relationship. * * @param mixed $ids * @param bool $touch * @return int */ public function detach($ids = null, $touch = true) { if ($this->using && ! empty($ids) && empty($this->pivotWheres) && empty($this->pivotWhereIns) && empty($this->pivotWhereNulls)) { $results = $this->detachUsingCustomClass($ids); } else { $query = $this->newPivotQuery(); // If associated IDs were passed to the method we will only delete those // associations, otherwise all of the association ties will be broken. // We'll return the numbers of affected rows when we do the deletes. if (! is_null($ids)) { $ids = $this->parseIds($ids); if (empty($ids)) { return 0; } $query->whereIn($this->getQualifiedRelatedPivotKeyName(), (array) $ids); } // Once we have all of the conditions set on the statement, we are ready // to run the delete on the pivot table. Then, if the touch parameter // is true, we will go ahead and touch all related models to sync. $results = $query->delete(); } if ($touch) { $this->touchIfTouching(); } return $results; } /** * Detach models from the relationship using a custom class. * * @param mixed $ids * @return int */ protected function detachUsingCustomClass($ids) { $results = 0; foreach ($this->parseIds($ids) as $id) { $results += $this->newPivot([ $this->foreignPivotKey => $this->parent->{$this->parentKey}, $this->relatedPivotKey => $id, ], true)->delete(); } return $results; } /** * Get the pivot models that are currently attached. * * @return \Illuminate\Support\Collection */ protected function getCurrentlyAttachedPivots() { return $this->newPivotQuery()->get()->map(function ($record) { $class = $this->using ?: Pivot::class; $pivot = $class::fromRawAttributes($this->parent, (array) $record, $this->getTable(), true); return $pivot->setPivotKeys($this->foreignPivotKey, $this->relatedPivotKey); }); } /** * Create a new pivot model instance. * * @param array $attributes * @param bool $exists * @return \Illuminate\Database\Eloquent\Relations\Pivot */ public function newPivot(array $attributes = [], $exists = false) { $pivot = $this->related->newPivot( $this->parent, $attributes, $this->table, $exists, $this->using ); return $pivot->setPivotKeys($this->foreignPivotKey, $this->relatedPivotKey); } /** * Create a new existing pivot model instance. * * @param array $attributes * @return \Illuminate\Database\Eloquent\Relations\Pivot */ public function newExistingPivot(array $attributes = []) { return $this->newPivot($attributes, true); } /** * Get a new plain query builder for the pivot table. * * @return \Illuminate\Database\Query\Builder */ public function newPivotStatement() { return $this->query->getQuery()->newQuery()->from($this->table); } /** * Get a new pivot statement for a given "other" ID. * * @param mixed $id * @return \Illuminate\Database\Query\Builder */ public function newPivotStatementForId($id) { return $this->newPivotQuery()->whereIn($this->relatedPivotKey, $this->parseIds($id)); } /** * Create a new query builder for the pivot table. * * @return \Illuminate\Database\Query\Builder */ public function newPivotQuery() { $query = $this->newPivotStatement(); foreach ($this->pivotWheres as $arguments) { $query->where(...$arguments); } foreach ($this->pivotWhereIns as $arguments) { $query->whereIn(...$arguments); } foreach ($this->pivotWhereNulls as $arguments) { $query->whereNull(...$arguments); } return $query->where($this->getQualifiedForeignPivotKeyName(), $this->parent->{$this->parentKey}); } /** * Set the columns on the pivot table to retrieve. * * @param array|mixed $columns * @return $this */ public function withPivot($columns) { $this->pivotColumns = array_merge( $this->pivotColumns, is_array($columns) ? $columns : func_get_args() ); return $this; } /** * Get all of the IDs from the given mixed value. * * @param mixed $value * @return array */ protected function parseIds($value) { if ($value instanceof Model) { return [$value->{$this->relatedKey}]; } if ($value instanceof Collection) { return $value->pluck($this->relatedKey)->all(); } if ($value instanceof BaseCollection) { return $value->toArray(); } return (array) $value; } /** * Get the ID from the given mixed value. * * @param mixed $value * @return mixed */ protected function parseId($value) { return $value instanceof Model ? $value->{$this->relatedKey} : $value; } /** * Cast the given keys to integers if they are numeric and string otherwise. * * @param array $keys * @return array */ protected function castKeys(array $keys) { return array_map(function ($v) { return $this->castKey($v); }, $keys); } /** * Cast the given key to convert to primary key type. * * @param mixed $key * @return mixed */ protected function castKey($key) { return $this->getTypeSwapValue( $this->related->getKeyType(), $key ); } /** * Cast the given pivot attributes. * * @param array $attributes * @return array */ protected function castAttributes($attributes) { return $this->using ? $this->newPivot()->fill($attributes)->getAttributes() : $attributes; } /** * Converts a given value to a given type value. * * @param string $type * @param mixed $value * @return mixed */ protected function getTypeSwapValue($type, $value) { switch (strtolower($type)) { case 'int': case 'integer': return (int) $value; case 'real': case 'float': case 'double': return (float) $value; case 'string': return (string) $value; default: return $value; } } } Concerns/CanBeOneOfMany.php000066600000022067150515304400011563 0ustar00isOneOfMany = true; $this->relationName = $relation ?: $this->getDefaultOneOfManyJoinAlias( $this->guessRelationship() ); $keyName = $this->query->getModel()->getKeyName(); $columns = is_string($columns = $column) ? [ $column => $aggregate, $keyName => $aggregate, ] : $column; if (! array_key_exists($keyName, $columns)) { $columns[$keyName] = 'MAX'; } if ($aggregate instanceof Closure) { $closure = $aggregate; } foreach ($columns as $column => $aggregate) { if (! in_array(strtolower($aggregate), ['min', 'max'])) { throw new InvalidArgumentException("Invalid aggregate [{$aggregate}] used within ofMany relation. Available aggregates: MIN, MAX"); } $subQuery = $this->newOneOfManySubQuery( $this->getOneOfManySubQuerySelectColumns(), $column, $aggregate ); if (isset($previous)) { $this->addOneOfManyJoinSubQuery($subQuery, $previous['subQuery'], $previous['column']); } if (isset($closure)) { $closure($subQuery); } if (! isset($previous)) { $this->oneOfManySubQuery = $subQuery; } if (array_key_last($columns) == $column) { $this->addOneOfManyJoinSubQuery($this->query, $subQuery, $column); } $previous = [ 'subQuery' => $subQuery, 'column' => $column, ]; } $this->addConstraints(); $columns = $this->query->getQuery()->columns; if (is_null($columns) || $columns === ['*']) { $this->select([$this->qualifyColumn('*')]); } return $this; } /** * Indicate that the relation is the latest single result of a larger one-to-many relationship. * * @param string|array|null $column * @param string|Closure|null $aggregate * @param string|null $relation * @return $this */ public function latestOfMany($column = 'id', $relation = null) { return $this->ofMany(collect(Arr::wrap($column))->mapWithKeys(function ($column) { return [$column => 'MAX']; })->all(), 'MAX', $relation); } /** * Indicate that the relation is the oldest single result of a larger one-to-many relationship. * * @param string|array|null $column * @param string|Closure|null $aggregate * @param string|null $relation * @return $this */ public function oldestOfMany($column = 'id', $relation = null) { return $this->ofMany(collect(Arr::wrap($column))->mapWithKeys(function ($column) { return [$column => 'MIN']; })->all(), 'MIN', $relation); } /** * Get the default alias for the one of many inner join clause. * * @param string $relation * @return string */ protected function getDefaultOneOfManyJoinAlias($relation) { return $relation == $this->query->getModel()->getTable() ? $relation.'_of_many' : $relation; } /** * Get a new query for the related model, grouping the query by the given column, often the foreign key of the relationship. * * @param string|array $groupBy * @param string|null $column * @param string|null $aggregate * @return \Illuminate\Database\Eloquent\Builder */ protected function newOneOfManySubQuery($groupBy, $column = null, $aggregate = null) { $subQuery = $this->query->getModel() ->newQuery() ->withoutGlobalScopes($this->removedScopes()); foreach (Arr::wrap($groupBy) as $group) { $subQuery->groupBy($this->qualifyRelatedColumn($group)); } if (! is_null($column)) { $subQuery->selectRaw($aggregate.'('.$subQuery->getQuery()->grammar->wrap($subQuery->qualifyColumn($column)).') as '.$subQuery->getQuery()->grammar->wrap($column.'_aggregate')); } $this->addOneOfManySubQueryConstraints($subQuery, $groupBy, $column, $aggregate); return $subQuery; } /** * Add the join subquery to the given query on the given column and the relationship's foreign key. * * @param \Illuminate\Database\Eloquent\Builder $parent * @param \Illuminate\Database\Eloquent\Builder $subQuery * @param string $on * @return void */ protected function addOneOfManyJoinSubQuery(Builder $parent, Builder $subQuery, $on) { $parent->beforeQuery(function ($parent) use ($subQuery, $on) { $subQuery->applyBeforeQueryCallbacks(); $parent->joinSub($subQuery, $this->relationName, function ($join) use ($on) { $join->on($this->qualifySubSelectColumn($on.'_aggregate'), '=', $this->qualifyRelatedColumn($on)); $this->addOneOfManyJoinSubQueryConstraints($join, $on); }); }); } /** * Merge the relationship query joins to the given query builder. * * @param \Illuminate\Database\Eloquent\Builder $builder * @return void */ protected function mergeOneOfManyJoinsTo(Builder $query) { $query->getQuery()->beforeQueryCallbacks = $this->query->getQuery()->beforeQueryCallbacks; $query->applyBeforeQueryCallbacks(); } /** * Get the query builder that will contain the relationship constraints. * * @return \Illuminate\Database\Eloquent\Builder */ protected function getRelationQuery() { return $this->isOneOfMany() ? $this->oneOfManySubQuery : $this->query; } /** * Get the one of many inner join subselect builder instance. * * @return \Illuminate\Database\Eloquent\Builder|void */ public function getOneOfManySubQuery() { return $this->oneOfManySubQuery; } /** * Get the qualified column name for the one-of-many relationship using the subselect join query's alias. * * @param string $column * @return string */ public function qualifySubSelectColumn($column) { return $this->getRelationName().'.'.last(explode('.', $column)); } /** * Qualify related column using the related table name if it is not already qualified. * * @param string $column * @return string */ protected function qualifyRelatedColumn($column) { return Str::contains($column, '.') ? $column : $this->query->getModel()->getTable().'.'.$column; } /** * Guess the "hasOne" relationship's name via backtrace. * * @return string */ protected function guessRelationship() { return debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3)[2]['function']; } /** * Determine whether the relationship is a one-of-many relationship. * * @return bool */ public function isOneOfMany() { return $this->isOneOfMany; } /** * Get the name of the relationship. * * @return string */ public function getRelationName() { return $this->relationName; } } Concerns/AsPivot.php000066600000020735150515304400010424 0ustar00timestamps = $instance->hasTimestampAttributes($attributes); // The pivot model is a "dynamic" model since we will set the tables dynamically // for the instance. This allows it work for any intermediate tables for the // many to many relationship that are defined by this developer's classes. $instance->setConnection($parent->getConnectionName()) ->setTable($table) ->forceFill($attributes) ->syncOriginal(); // We store off the parent instance so we will access the timestamp column names // for the model, since the pivot model timestamps aren't easily configurable // from the developer's point of view. We can use the parents to get these. $instance->pivotParent = $parent; $instance->exists = $exists; return $instance; } /** * Create a new pivot model from raw values returned from a query. * * @param \Illuminate\Database\Eloquent\Model $parent * @param array $attributes * @param string $table * @param bool $exists * @return static */ public static function fromRawAttributes(Model $parent, $attributes, $table, $exists = false) { $instance = static::fromAttributes($parent, [], $table, $exists); $instance->timestamps = $instance->hasTimestampAttributes($attributes); $instance->setRawAttributes($attributes, $exists); return $instance; } /** * Set the keys for a select query. * * @param \Illuminate\Database\Eloquent\Builder $query * @return \Illuminate\Database\Eloquent\Builder */ protected function setKeysForSelectQuery($query) { if (isset($this->attributes[$this->getKeyName()])) { return parent::setKeysForSelectQuery($query); } $query->where($this->foreignKey, $this->getOriginal( $this->foreignKey, $this->getAttribute($this->foreignKey) )); return $query->where($this->relatedKey, $this->getOriginal( $this->relatedKey, $this->getAttribute($this->relatedKey) )); } /** * Set the keys for a save update query. * * @param \Illuminate\Database\Eloquent\Builder $query * @return \Illuminate\Database\Eloquent\Builder */ protected function setKeysForSaveQuery($query) { return $this->setKeysForSelectQuery($query); } /** * Delete the pivot model record from the database. * * @return int */ public function delete() { if (isset($this->attributes[$this->getKeyName()])) { return (int) parent::delete(); } if ($this->fireModelEvent('deleting') === false) { return 0; } $this->touchOwners(); return tap($this->getDeleteQuery()->delete(), function () { $this->exists = false; $this->fireModelEvent('deleted', false); }); } /** * Get the query builder for a delete operation on the pivot. * * @return \Illuminate\Database\Eloquent\Builder */ protected function getDeleteQuery() { return $this->newQueryWithoutRelationships()->where([ $this->foreignKey => $this->getOriginal($this->foreignKey, $this->getAttribute($this->foreignKey)), $this->relatedKey => $this->getOriginal($this->relatedKey, $this->getAttribute($this->relatedKey)), ]); } /** * Get the table associated with the model. * * @return string */ public function getTable() { if (! isset($this->table)) { $this->setTable(str_replace( '\\', '', Str::snake(Str::singular(class_basename($this))) )); } return $this->table; } /** * Get the foreign key column name. * * @return string */ public function getForeignKey() { return $this->foreignKey; } /** * Get the "related key" column name. * * @return string */ public function getRelatedKey() { return $this->relatedKey; } /** * Get the "related key" column name. * * @return string */ public function getOtherKey() { return $this->getRelatedKey(); } /** * Set the key names for the pivot model instance. * * @param string $foreignKey * @param string $relatedKey * @return $this */ public function setPivotKeys($foreignKey, $relatedKey) { $this->foreignKey = $foreignKey; $this->relatedKey = $relatedKey; return $this; } /** * Determine if the pivot model or given attributes has timestamp attributes. * * @param array|null $attributes * @return bool */ public function hasTimestampAttributes($attributes = null) { return array_key_exists($this->getCreatedAtColumn(), $attributes ?? $this->attributes); } /** * Get the name of the "created at" column. * * @return string */ public function getCreatedAtColumn() { return $this->pivotParent ? $this->pivotParent->getCreatedAtColumn() : parent::getCreatedAtColumn(); } /** * Get the name of the "updated at" column. * * @return string */ public function getUpdatedAtColumn() { return $this->pivotParent ? $this->pivotParent->getUpdatedAtColumn() : parent::getUpdatedAtColumn(); } /** * Get the queueable identity for the entity. * * @return mixed */ public function getQueueableId() { if (isset($this->attributes[$this->getKeyName()])) { return $this->getKey(); } return sprintf( '%s:%s:%s:%s', $this->foreignKey, $this->getAttribute($this->foreignKey), $this->relatedKey, $this->getAttribute($this->relatedKey) ); } /** * Get a new query to restore one or more models by their queueable IDs. * * @param int[]|string[]|string $ids * @return \Illuminate\Database\Eloquent\Builder */ public function newQueryForRestoration($ids) { if (is_array($ids)) { return $this->newQueryForCollectionRestoration($ids); } if (! Str::contains($ids, ':')) { return parent::newQueryForRestoration($ids); } $segments = explode(':', $ids); return $this->newQueryWithoutScopes() ->where($segments[0], $segments[1]) ->where($segments[2], $segments[3]); } /** * Get a new query to restore multiple models by their queueable IDs. * * @param int[]|string[] $ids * @return \Illuminate\Database\Eloquent\Builder */ protected function newQueryForCollectionRestoration(array $ids) { $ids = array_values($ids); if (! Str::contains($ids[0], ':')) { return parent::newQueryForRestoration($ids); } $query = $this->newQueryWithoutScopes(); foreach ($ids as $id) { $segments = explode(':', $id); $query->orWhere(function ($query) use ($segments) { return $query->where($segments[0], $segments[1]) ->where($segments[2], $segments[3]); }); } return $query; } /** * Unset all the loaded relations for the instance. * * @return $this */ public function unsetRelations() { $this->pivotParent = null; $this->relations = []; return $this; } } Concerns/SupportsDefaultModels.php000066600000003021150515304400013334 0ustar00withDefault = $callback; return $this; } /** * Get the default value for this relation. * * @param \Illuminate\Database\Eloquent\Model $parent * @return \Illuminate\Database\Eloquent\Model|null */ protected function getDefaultFor(Model $parent) { if (! $this->withDefault) { return; } $instance = $this->newRelatedInstanceFor($parent); if (is_callable($this->withDefault)) { return call_user_func($this->withDefault, $instance, $parent) ?: $instance; } if (is_array($this->withDefault)) { $instance->forceFill($this->withDefault); } return $instance; } } Pivot.php000066600000000707150515304400006363 0ustar00where($this->morphType, $this->morphClass); return parent::setKeysForSaveQuery($query); } /** * Set the keys for a select query. * * @param \Illuminate\Database\Eloquent\Builder $query * @return \Illuminate\Database\Eloquent\Builder */ protected function setKeysForSelectQuery($query) { $query->where($this->morphType, $this->morphClass); return parent::setKeysForSelectQuery($query); } /** * Delete the pivot model record from the database. * * @return int */ public function delete() { if (isset($this->attributes[$this->getKeyName()])) { return (int) parent::delete(); } if ($this->fireModelEvent('deleting') === false) { return 0; } $query = $this->getDeleteQuery(); $query->where($this->morphType, $this->morphClass); return tap($query->delete(), function () { $this->fireModelEvent('deleted', false); }); } /** * Get the morph type for the pivot. * * @return string */ public function getMorphType() { return $this->morphType; } /** * Set the morph type for the pivot. * * @param string $morphType * @return $this */ public function setMorphType($morphType) { $this->morphType = $morphType; return $this; } /** * Set the morph class for the pivot. * * @param string $morphClass * @return \Illuminate\Database\Eloquent\Relations\MorphPivot */ public function setMorphClass($morphClass) { $this->morphClass = $morphClass; return $this; } /** * Get the queueable identity for the entity. * * @return mixed */ public function getQueueableId() { if (isset($this->attributes[$this->getKeyName()])) { return $this->getKey(); } return sprintf( '%s:%s:%s:%s:%s:%s', $this->foreignKey, $this->getAttribute($this->foreignKey), $this->relatedKey, $this->getAttribute($this->relatedKey), $this->morphType, $this->morphClass ); } /** * Get a new query to restore one or more models by their queueable IDs. * * @param array|int $ids * @return \Illuminate\Database\Eloquent\Builder */ public function newQueryForRestoration($ids) { if (is_array($ids)) { return $this->newQueryForCollectionRestoration($ids); } if (! Str::contains($ids, ':')) { return parent::newQueryForRestoration($ids); } $segments = explode(':', $ids); return $this->newQueryWithoutScopes() ->where($segments[0], $segments[1]) ->where($segments[2], $segments[3]) ->where($segments[4], $segments[5]); } /** * Get a new query to restore multiple models by their queueable IDs. * * @param array $ids * @return \Illuminate\Database\Eloquent\Builder */ protected function newQueryForCollectionRestoration(array $ids) { $ids = array_values($ids); if (! Str::contains($ids[0], ':')) { return parent::newQueryForRestoration($ids); } $query = $this->newQueryWithoutScopes(); foreach ($ids as $id) { $segments = explode(':', $id); $query->orWhere(function ($query) use ($segments) { return $query->where($segments[0], $segments[1]) ->where($segments[2], $segments[3]) ->where($segments[4], $segments[5]); }); } return $query; } } MorphOne.php000066600000010257150515304400007012 0ustar00getParentKey())) { return $this->getDefaultFor($this->parent); } return $this->query->first() ?: $this->getDefaultFor($this->parent); } /** * Initialize the relation on a set of models. * * @param array $models * @param string $relation * @return array */ public function initRelation(array $models, $relation) { foreach ($models as $model) { $model->setRelation($relation, $this->getDefaultFor($model)); } return $models; } /** * Match the eagerly loaded results to their parents. * * @param array $models * @param \Illuminate\Database\Eloquent\Collection $results * @param string $relation * @return array */ public function match(array $models, Collection $results, $relation) { return $this->matchOne($models, $results, $relation); } /** * Get the relationship query. * * @param \Illuminate\Database\Eloquent\Builder $query * @param \Illuminate\Database\Eloquent\Builder $parentQuery * @param array|mixed $columns * @return \Illuminate\Database\Eloquent\Builder */ public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*']) { if ($this->isOneOfMany()) { $this->mergeOneOfManyJoinsTo($query); } return parent::getRelationExistenceQuery($query, $parentQuery, $columns); } /** * Add constraints for inner join subselect for one of many relationships. * * @param \Illuminate\Database\Eloquent\Builder $query * @param string|null $column * @param string|null $aggregate * @return void */ public function addOneOfManySubQueryConstraints(Builder $query, $column = null, $aggregate = null) { $query->addSelect($this->foreignKey, $this->morphType); } /** * Get the columns that should be selected by the one of many subquery. * * @return array|string */ public function getOneOfManySubQuerySelectColumns() { return [$this->foreignKey, $this->morphType]; } /** * Add join query constraints for one of many relationships. * * @param \Illuminate\Database\Eloquent\JoinClause $join * @return void */ public function addOneOfManyJoinSubQueryConstraints(JoinClause $join) { $join ->on($this->qualifySubSelectColumn($this->morphType), '=', $this->qualifyRelatedColumn($this->morphType)) ->on($this->qualifySubSelectColumn($this->foreignKey), '=', $this->qualifyRelatedColumn($this->foreignKey)); } /** * Make a new related instance for the given model. * * @param \Illuminate\Database\Eloquent\Model $parent * @return \Illuminate\Database\Eloquent\Model */ public function newRelatedInstanceFor(Model $parent) { return $this->related->newInstance() ->setAttribute($this->getForeignKeyName(), $parent->{$this->localKey}) ->setAttribute($this->getMorphType(), $this->morphClass); } /** * Get the value of the model's foreign key. * * @param \Illuminate\Database\Eloquent\Model $model * @return mixed */ protected function getRelatedKeyFrom(Model $model) { return $model->getAttribute($this->getForeignKeyName()); } } MorphToMany.php000066600000013243150515304400007476 0ustar00inverse = $inverse; $this->morphType = $name.'_type'; $this->morphClass = $inverse ? $query->getModel()->getMorphClass() : $parent->getMorphClass(); parent::__construct( $query, $parent, $table, $foreignPivotKey, $relatedPivotKey, $parentKey, $relatedKey, $relationName ); } /** * Set the where clause for the relation query. * * @return $this */ protected function addWhereConstraints() { parent::addWhereConstraints(); $this->query->where($this->qualifyPivotColumn($this->morphType), $this->morphClass); return $this; } /** * Set the constraints for an eager load of the relation. * * @param array $models * @return void */ public function addEagerConstraints(array $models) { parent::addEagerConstraints($models); $this->query->where($this->qualifyPivotColumn($this->morphType), $this->morphClass); } /** * Create a new pivot attachment record. * * @param int $id * @param bool $timed * @return array */ protected function baseAttachRecord($id, $timed) { return Arr::add( parent::baseAttachRecord($id, $timed), $this->morphType, $this->morphClass ); } /** * Add the constraints for a relationship count query. * * @param \Illuminate\Database\Eloquent\Builder $query * @param \Illuminate\Database\Eloquent\Builder $parentQuery * @param array|mixed $columns * @return \Illuminate\Database\Eloquent\Builder */ public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*']) { return parent::getRelationExistenceQuery($query, $parentQuery, $columns)->where( $this->qualifyPivotColumn($this->morphType), $this->morphClass ); } /** * Get the pivot models that are currently attached. * * @return \Illuminate\Support\Collection */ protected function getCurrentlyAttachedPivots() { return parent::getCurrentlyAttachedPivots()->map(function ($record) { return $record instanceof MorphPivot ? $record->setMorphType($this->morphType) ->setMorphClass($this->morphClass) : $record; }); } /** * Create a new query builder for the pivot table. * * @return \Illuminate\Database\Query\Builder */ public function newPivotQuery() { return parent::newPivotQuery()->where($this->morphType, $this->morphClass); } /** * Create a new pivot model instance. * * @param array $attributes * @param bool $exists * @return \Illuminate\Database\Eloquent\Relations\Pivot */ public function newPivot(array $attributes = [], $exists = false) { $using = $this->using; $pivot = $using ? $using::fromRawAttributes($this->parent, $attributes, $this->table, $exists) : MorphPivot::fromAttributes($this->parent, $attributes, $this->table, $exists); $pivot->setPivotKeys($this->foreignPivotKey, $this->relatedPivotKey) ->setMorphType($this->morphType) ->setMorphClass($this->morphClass); return $pivot; } /** * Get the pivot columns for the relation. * * "pivot_" is prefixed at each column for easy removal later. * * @return array */ protected function aliasedPivotColumns() { $defaults = [$this->foreignPivotKey, $this->relatedPivotKey, $this->morphType]; return collect(array_merge($defaults, $this->pivotColumns))->map(function ($column) { return $this->qualifyPivotColumn($column).' as pivot_'.$column; })->unique()->all(); } /** * Get the foreign key "type" name. * * @return string */ public function getMorphType() { return $this->morphType; } /** * Get the class name of the parent model. * * @return string */ public function getMorphClass() { return $this->morphClass; } /** * Get the indicator for a reverse relationship. * * @return bool */ public function getInverse() { return $this->inverse; } } BelongsTo.php000066600000025277150515304400007167 0ustar00ownerKey = $ownerKey; $this->relationName = $relationName; $this->foreignKey = $foreignKey; // In the underlying base relationship class, this variable is referred to as // the "parent" since most relationships are not inversed. But, since this // one is we will create a "child" variable for much better readability. $this->child = $child; parent::__construct($query, $child); } /** * Get the results of the relationship. * * @return mixed */ public function getResults() { if (is_null($this->child->{$this->foreignKey})) { return $this->getDefaultFor($this->parent); } return $this->query->first() ?: $this->getDefaultFor($this->parent); } /** * Set the base constraints on the relation query. * * @return void */ public function addConstraints() { if (static::$constraints) { // For belongs to relationships, which are essentially the inverse of has one // or has many relationships, we need to actually query on the primary key // of the related models matching on the foreign key that's on a parent. $table = $this->related->getTable(); $this->query->where($table.'.'.$this->ownerKey, '=', $this->child->{$this->foreignKey}); } } /** * Set the constraints for an eager load of the relation. * * @param array $models * @return void */ public function addEagerConstraints(array $models) { // We'll grab the primary key name of the related models since it could be set to // a non-standard name and not "id". We will then construct the constraint for // our eagerly loading query so it returns the proper models from execution. $key = $this->related->getTable().'.'.$this->ownerKey; $whereIn = $this->whereInMethod($this->related, $this->ownerKey); $this->query->{$whereIn}($key, $this->getEagerModelKeys($models)); } /** * Gather the keys from an array of related models. * * @param array $models * @return array */ protected function getEagerModelKeys(array $models) { $keys = []; // First we need to gather all of the keys from the parent models so we know what // to query for via the eager loading query. We will add them to an array then // execute a "where in" statement to gather up all of those related records. foreach ($models as $model) { if (! is_null($value = $model->{$this->foreignKey})) { $keys[] = $value; } } sort($keys); return array_values(array_unique($keys)); } /** * Initialize the relation on a set of models. * * @param array $models * @param string $relation * @return array */ public function initRelation(array $models, $relation) { foreach ($models as $model) { $model->setRelation($relation, $this->getDefaultFor($model)); } return $models; } /** * Match the eagerly loaded results to their parents. * * @param array $models * @param \Illuminate\Database\Eloquent\Collection $results * @param string $relation * @return array */ public function match(array $models, Collection $results, $relation) { $foreign = $this->foreignKey; $owner = $this->ownerKey; // First we will get to build a dictionary of the child models by their primary // key of the relationship, then we can easily match the children back onto // the parents using that dictionary and the primary key of the children. $dictionary = []; foreach ($results as $result) { $attribute = $this->getDictionaryKey($result->getAttribute($owner)); $dictionary[$attribute] = $result; } // Once we have the dictionary constructed, we can loop through all the parents // and match back onto their children using these keys of the dictionary and // the primary key of the children to map them onto the correct instances. foreach ($models as $model) { $attribute = $this->getDictionaryKey($model->{$foreign}); if (isset($dictionary[$attribute])) { $model->setRelation($relation, $dictionary[$attribute]); } } return $models; } /** * Associate the model instance to the given parent. * * @param \Illuminate\Database\Eloquent\Model|int|string|null $model * @return \Illuminate\Database\Eloquent\Model */ public function associate($model) { $ownerKey = $model instanceof Model ? $model->getAttribute($this->ownerKey) : $model; $this->child->setAttribute($this->foreignKey, $ownerKey); if ($model instanceof Model) { $this->child->setRelation($this->relationName, $model); } else { $this->child->unsetRelation($this->relationName); } return $this->child; } /** * Dissociate previously associated model from the given parent. * * @return \Illuminate\Database\Eloquent\Model */ public function dissociate() { $this->child->setAttribute($this->foreignKey, null); return $this->child->setRelation($this->relationName, null); } /** * Alias of "dissociate" method. * * @return \Illuminate\Database\Eloquent\Model */ public function disassociate() { return $this->dissociate(); } /** * Add the constraints for a relationship query. * * @param \Illuminate\Database\Eloquent\Builder $query * @param \Illuminate\Database\Eloquent\Builder $parentQuery * @param array|mixed $columns * @return \Illuminate\Database\Eloquent\Builder */ public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*']) { if ($parentQuery->getQuery()->from == $query->getQuery()->from) { return $this->getRelationExistenceQueryForSelfRelation($query, $parentQuery, $columns); } return $query->select($columns)->whereColumn( $this->getQualifiedForeignKeyName(), '=', $query->qualifyColumn($this->ownerKey) ); } /** * Add the constraints for a relationship query on the same table. * * @param \Illuminate\Database\Eloquent\Builder $query * @param \Illuminate\Database\Eloquent\Builder $parentQuery * @param array|mixed $columns * @return \Illuminate\Database\Eloquent\Builder */ public function getRelationExistenceQueryForSelfRelation(Builder $query, Builder $parentQuery, $columns = ['*']) { $query->select($columns)->from( $query->getModel()->getTable().' as '.$hash = $this->getRelationCountHash() ); $query->getModel()->setTable($hash); return $query->whereColumn( $hash.'.'.$this->ownerKey, '=', $this->getQualifiedForeignKeyName() ); } /** * Determine if the related model has an auto-incrementing ID. * * @return bool */ protected function relationHasIncrementingId() { return $this->related->getIncrementing() && in_array($this->related->getKeyType(), ['int', 'integer']); } /** * Make a new related instance for the given model. * * @param \Illuminate\Database\Eloquent\Model $parent * @return \Illuminate\Database\Eloquent\Model */ protected function newRelatedInstanceFor(Model $parent) { return $this->related->newInstance(); } /** * Get the child of the relationship. * * @return \Illuminate\Database\Eloquent\Model */ public function getChild() { return $this->child; } /** * Get the foreign key of the relationship. * * @return string */ public function getForeignKeyName() { return $this->foreignKey; } /** * Get the fully qualified foreign key of the relationship. * * @return string */ public function getQualifiedForeignKeyName() { return $this->child->qualifyColumn($this->foreignKey); } /** * Get the key value of the child's foreign key. * * @return mixed */ public function getParentKey() { return $this->child->{$this->foreignKey}; } /** * Get the associated key of the relationship. * * @return string */ public function getOwnerKeyName() { return $this->ownerKey; } /** * Get the fully qualified associated key of the relationship. * * @return string */ public function getQualifiedOwnerKeyName() { return $this->related->qualifyColumn($this->ownerKey); } /** * Get the value of the model's associated key. * * @param \Illuminate\Database\Eloquent\Model $model * @return mixed */ protected function getRelatedKeyFrom(Model $model) { return $model->{$this->ownerKey}; } /** * Get the name of the relationship. * * @return string */ public function getRelationName() { return $this->relationName; } } MorphOneOrMany.php000066600000006077150515304400010145 0ustar00morphType = $type; $this->morphClass = $parent->getMorphClass(); parent::__construct($query, $parent, $id, $localKey); } /** * Set the base constraints on the relation query. * * @return void */ public function addConstraints() { if (static::$constraints) { $this->getRelationQuery()->where($this->morphType, $this->morphClass); parent::addConstraints(); } } /** * Set the constraints for an eager load of the relation. * * @param array $models * @return void */ public function addEagerConstraints(array $models) { parent::addEagerConstraints($models); $this->getRelationQuery()->where($this->morphType, $this->morphClass); } /** * Set the foreign ID and type for creating a related model. * * @param \Illuminate\Database\Eloquent\Model $model * @return void */ protected function setForeignAttributesForCreate(Model $model) { $model->{$this->getForeignKeyName()} = $this->getParentKey(); $model->{$this->getMorphType()} = $this->morphClass; } /** * Get the relationship query. * * @param \Illuminate\Database\Eloquent\Builder $query * @param \Illuminate\Database\Eloquent\Builder $parentQuery * @param array|mixed $columns * @return \Illuminate\Database\Eloquent\Builder */ public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*']) { return parent::getRelationExistenceQuery($query, $parentQuery, $columns)->where( $query->qualifyColumn($this->getMorphType()), $this->morphClass ); } /** * Get the foreign key "type" name. * * @return string */ public function getQualifiedMorphType() { return $this->morphType; } /** * Get the plain morph type name without the table. * * @return string */ public function getMorphType() { return last(explode('.', $this->morphType)); } /** * Get the class name of the parent model. * * @return string */ public function getMorphClass() { return $this->morphClass; } } Relation.php000066600000030304150515304400007033 0ustar00query = $query; $this->parent = $parent; $this->related = $query->getModel(); $this->addConstraints(); } /** * Run a callback with constraints disabled on the relation. * * @param \Closure $callback * @return mixed */ public static function noConstraints(Closure $callback) { $previous = static::$constraints; static::$constraints = false; // When resetting the relation where clause, we want to shift the first element // off of the bindings, leaving only the constraints that the developers put // as "extra" on the relationships, and not original relation constraints. try { return $callback(); } finally { static::$constraints = $previous; } } /** * Set the base constraints on the relation query. * * @return void */ abstract public function addConstraints(); /** * Set the constraints for an eager load of the relation. * * @param array $models * @return void */ abstract public function addEagerConstraints(array $models); /** * Initialize the relation on a set of models. * * @param array $models * @param string $relation * @return array */ abstract public function initRelation(array $models, $relation); /** * Match the eagerly loaded results to their parents. * * @param array $models * @param \Illuminate\Database\Eloquent\Collection $results * @param string $relation * @return array */ abstract public function match(array $models, Collection $results, $relation); /** * Get the results of the relationship. * * @return mixed */ abstract public function getResults(); /** * Get the relationship for eager loading. * * @return \Illuminate\Database\Eloquent\Collection */ public function getEager() { return $this->get(); } /** * Execute the query and get the first result if it's the sole matching record. * * @param array|string $columns * @return \Illuminate\Database\Eloquent\Model * * @throws \Illuminate\Database\Eloquent\ModelNotFoundException * @throws \Illuminate\Database\MultipleRecordsFoundException */ public function sole($columns = ['*']) { $result = $this->take(2)->get($columns); if ($result->isEmpty()) { throw (new ModelNotFoundException)->setModel(get_class($this->related)); } if ($result->count() > 1) { throw new MultipleRecordsFoundException; } return $result->first(); } /** * Execute the query as a "select" statement. * * @param array $columns * @return \Illuminate\Database\Eloquent\Collection */ public function get($columns = ['*']) { return $this->query->get($columns); } /** * Touch all of the related models for the relationship. * * @return void */ public function touch() { $model = $this->getRelated(); if (! $model::isIgnoringTouch()) { $this->rawUpdate([ $model->getUpdatedAtColumn() => $model->freshTimestampString(), ]); } } /** * Run a raw update against the base query. * * @param array $attributes * @return int */ public function rawUpdate(array $attributes = []) { return $this->query->withoutGlobalScopes()->update($attributes); } /** * Add the constraints for a relationship count query. * * @param \Illuminate\Database\Eloquent\Builder $query * @param \Illuminate\Database\Eloquent\Builder $parentQuery * @return \Illuminate\Database\Eloquent\Builder */ public function getRelationExistenceCountQuery(Builder $query, Builder $parentQuery) { return $this->getRelationExistenceQuery( $query, $parentQuery, new Expression('count(*)') )->setBindings([], 'select'); } /** * Add the constraints for an internal relationship existence query. * * Essentially, these queries compare on column names like whereColumn. * * @param \Illuminate\Database\Eloquent\Builder $query * @param \Illuminate\Database\Eloquent\Builder $parentQuery * @param array|mixed $columns * @return \Illuminate\Database\Eloquent\Builder */ public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*']) { return $query->select($columns)->whereColumn( $this->getQualifiedParentKeyName(), '=', $this->getExistenceCompareKey() ); } /** * Get a relationship join table hash. * * @param bool $incrementJoinCount * @return string */ public function getRelationCountHash($incrementJoinCount = true) { return 'laravel_reserved_'.($incrementJoinCount ? static::$selfJoinCount++ : static::$selfJoinCount); } /** * Get all of the primary keys for an array of models. * * @param array $models * @param string|null $key * @return array */ protected function getKeys(array $models, $key = null) { return collect($models)->map(function ($value) use ($key) { return $key ? $value->getAttribute($key) : $value->getKey(); })->values()->unique(null, true)->sort()->all(); } /** * Get the query builder that will contain the relationship constraints. * * @return \Illuminate\Database\Eloquent\Builder */ protected function getRelationQuery() { return $this->query; } /** * Get the underlying query for the relation. * * @return \Illuminate\Database\Eloquent\Builder */ public function getQuery() { return $this->query; } /** * Get the base query builder driving the Eloquent builder. * * @return \Illuminate\Database\Query\Builder */ public function getBaseQuery() { return $this->query->getQuery(); } /** * Get the parent model of the relation. * * @return \Illuminate\Database\Eloquent\Model */ public function getParent() { return $this->parent; } /** * Get the fully qualified parent key name. * * @return string */ public function getQualifiedParentKeyName() { return $this->parent->getQualifiedKeyName(); } /** * Get the related model of the relation. * * @return \Illuminate\Database\Eloquent\Model */ public function getRelated() { return $this->related; } /** * Get the name of the "created at" column. * * @return string */ public function createdAt() { return $this->parent->getCreatedAtColumn(); } /** * Get the name of the "updated at" column. * * @return string */ public function updatedAt() { return $this->parent->getUpdatedAtColumn(); } /** * Get the name of the related model's "updated at" column. * * @return string */ public function relatedUpdatedAt() { return $this->related->getUpdatedAtColumn(); } /** * Get the name of the "where in" method for eager loading. * * @param \Illuminate\Database\Eloquent\Model $model * @param string $key * @return string */ protected function whereInMethod(Model $model, $key) { return $model->getKeyName() === last(explode('.', $key)) && in_array($model->getKeyType(), ['int', 'integer']) ? 'whereIntegerInRaw' : 'whereIn'; } /** * Prevent polymorphic relationships from being used without model mappings. * * @param bool $requireMorphMap * @return void */ public static function requireMorphMap($requireMorphMap = true) { static::$requireMorphMap = $requireMorphMap; } /** * Determine if polymorphic relationships require explicit model mapping. * * @return bool */ public static function requiresMorphMap() { return static::$requireMorphMap; } /** * Define the morph map for polymorphic relations and require all morphed models to be explicitly mapped. * * @param array $map * @param bool $merge * @return array */ public static function enforceMorphMap(array $map, $merge = true) { static::requireMorphMap(); return static::morphMap($map, $merge); } /** * Set or get the morph map for polymorphic relations. * * @param array|null $map * @param bool $merge * @return array */ public static function morphMap(array $map = null, $merge = true) { $map = static::buildMorphMapFromModels($map); if (is_array($map)) { static::$morphMap = $merge && static::$morphMap ? $map + static::$morphMap : $map; } return static::$morphMap; } /** * Builds a table-keyed array from model class names. * * @param string[]|null $models * @return array|null */ protected static function buildMorphMapFromModels(array $models = null) { if (is_null($models) || Arr::isAssoc($models)) { return $models; } return array_combine(array_map(function ($model) { return (new $model)->getTable(); }, $models), $models); } /** * Get the model associated with a custom polymorphic type. * * @param string $alias * @return string|null */ public static function getMorphedModel($alias) { return static::$morphMap[$alias] ?? null; } /** * Handle dynamic method calls to the relationship. * * @param string $method * @param array $parameters * @return mixed */ public function __call($method, $parameters) { if (static::hasMacro($method)) { return $this->macroCall($method, $parameters); } return $this->forwardDecoratedCallTo($this->query, $method, $parameters); } /** * Force a clone of the underlying query builder when cloning. * * @return void */ public function __clone() { $this->query = clone $this->query; } } BelongsToMany.php000066600000114272150515304400010006 0ustar00parentKey = $parentKey; $this->relatedKey = $relatedKey; $this->relationName = $relationName; $this->relatedPivotKey = $relatedPivotKey; $this->foreignPivotKey = $foreignPivotKey; $this->table = $this->resolveTableName($table); parent::__construct($query, $parent); } /** * Attempt to resolve the intermediate table name from the given string. * * @param string $table * @return string */ protected function resolveTableName($table) { if (! Str::contains($table, '\\') || ! class_exists($table)) { return $table; } $model = new $table; if (! $model instanceof Model) { return $table; } if (in_array(AsPivot::class, class_uses_recursive($model))) { $this->using($table); } return $model->getTable(); } /** * Set the base constraints on the relation query. * * @return void */ public function addConstraints() { $this->performJoin(); if (static::$constraints) { $this->addWhereConstraints(); } } /** * Set the join clause for the relation query. * * @param \Illuminate\Database\Eloquent\Builder|null $query * @return $this */ protected function performJoin($query = null) { $query = $query ?: $this->query; // We need to join to the intermediate table on the related model's primary // key column with the intermediate table's foreign key for the related // model instance. Then we can set the "where" for the parent models. $query->join( $this->table, $this->getQualifiedRelatedKeyName(), '=', $this->getQualifiedRelatedPivotKeyName() ); return $this; } /** * Set the where clause for the relation query. * * @return $this */ protected function addWhereConstraints() { $this->query->where( $this->getQualifiedForeignPivotKeyName(), '=', $this->parent->{$this->parentKey} ); return $this; } /** * Set the constraints for an eager load of the relation. * * @param array $models * @return void */ public function addEagerConstraints(array $models) { $whereIn = $this->whereInMethod($this->parent, $this->parentKey); $this->query->{$whereIn}( $this->getQualifiedForeignPivotKeyName(), $this->getKeys($models, $this->parentKey) ); } /** * Initialize the relation on a set of models. * * @param array $models * @param string $relation * @return array */ public function initRelation(array $models, $relation) { foreach ($models as $model) { $model->setRelation($relation, $this->related->newCollection()); } return $models; } /** * Match the eagerly loaded results to their parents. * * @param array $models * @param \Illuminate\Database\Eloquent\Collection $results * @param string $relation * @return array */ public function match(array $models, Collection $results, $relation) { $dictionary = $this->buildDictionary($results); // Once we have an array dictionary of child objects we can easily match the // children back to their parent using the dictionary and the keys on the // parent models. Then we should return these hydrated models back out. foreach ($models as $model) { $key = $this->getDictionaryKey($model->{$this->parentKey}); if (isset($dictionary[$key])) { $model->setRelation( $relation, $this->related->newCollection($dictionary[$key]) ); } } return $models; } /** * Build model dictionary keyed by the relation's foreign key. * * @param \Illuminate\Database\Eloquent\Collection $results * @return array */ protected function buildDictionary(Collection $results) { // First we will build a dictionary of child models keyed by the foreign key // of the relation so that we will easily and quickly match them to their // parents without having a possibly slow inner loops for every models. $dictionary = []; foreach ($results as $result) { $value = $this->getDictionaryKey($result->{$this->accessor}->{$this->foreignPivotKey}); $dictionary[$value][] = $result; } return $dictionary; } /** * Get the class being used for pivot models. * * @return string */ public function getPivotClass() { return $this->using ?? Pivot::class; } /** * Specify the custom pivot model to use for the relationship. * * @param string $class * @return $this */ public function using($class) { $this->using = $class; return $this; } /** * Specify the custom pivot accessor to use for the relationship. * * @param string $accessor * @return $this */ public function as($accessor) { $this->accessor = $accessor; return $this; } /** * Set a where clause for a pivot table column. * * @param string $column * @param mixed $operator * @param mixed $value * @param string $boolean * @return $this */ public function wherePivot($column, $operator = null, $value = null, $boolean = 'and') { $this->pivotWheres[] = func_get_args(); return $this->where($this->qualifyPivotColumn($column), $operator, $value, $boolean); } /** * Set a "where between" clause for a pivot table column. * * @param string $column * @param array $values * @param string $boolean * @param bool $not * @return $this */ public function wherePivotBetween($column, array $values, $boolean = 'and', $not = false) { return $this->whereBetween($this->qualifyPivotColumn($column), $values, $boolean, $not); } /** * Set a "or where between" clause for a pivot table column. * * @param string $column * @param array $values * @return $this */ public function orWherePivotBetween($column, array $values) { return $this->wherePivotBetween($column, $values, 'or'); } /** * Set a "where pivot not between" clause for a pivot table column. * * @param string $column * @param array $values * @param string $boolean * @return $this */ public function wherePivotNotBetween($column, array $values, $boolean = 'and') { return $this->wherePivotBetween($column, $values, $boolean, true); } /** * Set a "or where not between" clause for a pivot table column. * * @param string $column * @param array $values * @return $this */ public function orWherePivotNotBetween($column, array $values) { return $this->wherePivotBetween($column, $values, 'or', true); } /** * Set a "where in" clause for a pivot table column. * * @param string $column * @param mixed $values * @param string $boolean * @param bool $not * @return $this */ public function wherePivotIn($column, $values, $boolean = 'and', $not = false) { $this->pivotWhereIns[] = func_get_args(); return $this->whereIn($this->qualifyPivotColumn($column), $values, $boolean, $not); } /** * Set an "or where" clause for a pivot table column. * * @param string $column * @param mixed $operator * @param mixed $value * @return $this */ public function orWherePivot($column, $operator = null, $value = null) { return $this->wherePivot($column, $operator, $value, 'or'); } /** * Set a where clause for a pivot table column. * * In addition, new pivot records will receive this value. * * @param string|array $column * @param mixed $value * @return $this * * @throws \InvalidArgumentException */ public function withPivotValue($column, $value = null) { if (is_array($column)) { foreach ($column as $name => $value) { $this->withPivotValue($name, $value); } return $this; } if (is_null($value)) { throw new InvalidArgumentException('The provided value may not be null.'); } $this->pivotValues[] = compact('column', 'value'); return $this->wherePivot($column, '=', $value); } /** * Set an "or where in" clause for a pivot table column. * * @param string $column * @param mixed $values * @return $this */ public function orWherePivotIn($column, $values) { return $this->wherePivotIn($column, $values, 'or'); } /** * Set a "where not in" clause for a pivot table column. * * @param string $column * @param mixed $values * @param string $boolean * @return $this */ public function wherePivotNotIn($column, $values, $boolean = 'and') { return $this->wherePivotIn($column, $values, $boolean, true); } /** * Set an "or where not in" clause for a pivot table column. * * @param string $column * @param mixed $values * @return $this */ public function orWherePivotNotIn($column, $values) { return $this->wherePivotNotIn($column, $values, 'or'); } /** * Set a "where null" clause for a pivot table column. * * @param string $column * @param string $boolean * @param bool $not * @return $this */ public function wherePivotNull($column, $boolean = 'and', $not = false) { $this->pivotWhereNulls[] = func_get_args(); return $this->whereNull($this->qualifyPivotColumn($column), $boolean, $not); } /** * Set a "where not null" clause for a pivot table column. * * @param string $column * @param string $boolean * @return $this */ public function wherePivotNotNull($column, $boolean = 'and') { return $this->wherePivotNull($column, $boolean, true); } /** * Set a "or where null" clause for a pivot table column. * * @param string $column * @param bool $not * @return $this */ public function orWherePivotNull($column, $not = false) { return $this->wherePivotNull($column, 'or', $not); } /** * Set a "or where not null" clause for a pivot table column. * * @param string $column * @return $this */ public function orWherePivotNotNull($column) { return $this->orWherePivotNull($column, true); } /** * Add an "order by" clause for a pivot table column. * * @param string $column * @param string $direction * @return $this */ public function orderByPivot($column, $direction = 'asc') { return $this->orderBy($this->qualifyPivotColumn($column), $direction); } /** * Find a related model by its primary key or return a new instance of the related model. * * @param mixed $id * @param array $columns * @return \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Model */ public function findOrNew($id, $columns = ['*']) { if (is_null($instance = $this->find($id, $columns))) { $instance = $this->related->newInstance(); } return $instance; } /** * Get the first related model record matching the attributes or instantiate it. * * @param array $attributes * @return \Illuminate\Database\Eloquent\Model */ public function firstOrNew(array $attributes) { if (is_null($instance = $this->where($attributes)->first())) { $instance = $this->related->newInstance($attributes); } return $instance; } /** * Get the first related record matching the attributes or create it. * * @param array $attributes * @param array $joining * @param bool $touch * @return \Illuminate\Database\Eloquent\Model */ public function firstOrCreate(array $attributes, array $joining = [], $touch = true) { if (is_null($instance = $this->where($attributes)->first())) { $instance = $this->create($attributes, $joining, $touch); } return $instance; } /** * Create or update a related record matching the attributes, and fill it with values. * * @param array $attributes * @param array $values * @param array $joining * @param bool $touch * @return \Illuminate\Database\Eloquent\Model */ public function updateOrCreate(array $attributes, array $values = [], array $joining = [], $touch = true) { if (is_null($instance = $this->where($attributes)->first())) { return $this->create($values, $joining, $touch); } $instance->fill($values); $instance->save(['touch' => false]); return $instance; } /** * Find a related model by its primary key. * * @param mixed $id * @param array $columns * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|null */ public function find($id, $columns = ['*']) { if (! $id instanceof Model && (is_array($id) || $id instanceof Arrayable)) { return $this->findMany($id, $columns); } return $this->where( $this->getRelated()->getQualifiedKeyName(), '=', $this->parseId($id) )->first($columns); } /** * Find multiple related models by their primary keys. * * @param \Illuminate\Contracts\Support\Arrayable|array $ids * @param array $columns * @return \Illuminate\Database\Eloquent\Collection */ public function findMany($ids, $columns = ['*']) { $ids = $ids instanceof Arrayable ? $ids->toArray() : $ids; if (empty($ids)) { return $this->getRelated()->newCollection(); } return $this->whereIn( $this->getRelated()->getQualifiedKeyName(), $this->parseIds($ids) )->get($columns); } /** * Find a related model by its primary key or throw an exception. * * @param mixed $id * @param array $columns * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection * * @throws \Illuminate\Database\Eloquent\ModelNotFoundException */ public function findOrFail($id, $columns = ['*']) { $result = $this->find($id, $columns); $id = $id instanceof Arrayable ? $id->toArray() : $id; if (is_array($id)) { if (count($result) === count(array_unique($id))) { return $result; } } elseif (! is_null($result)) { return $result; } throw (new ModelNotFoundException)->setModel(get_class($this->related), $id); } /** * Add a basic where clause to the query, and return the first result. * * @param \Closure|string|array $column * @param mixed $operator * @param mixed $value * @param string $boolean * @return \Illuminate\Database\Eloquent\Model|static */ public function firstWhere($column, $operator = null, $value = null, $boolean = 'and') { return $this->where($column, $operator, $value, $boolean)->first(); } /** * Execute the query and get the first result. * * @param array $columns * @return mixed */ public function first($columns = ['*']) { $results = $this->take(1)->get($columns); return count($results) > 0 ? $results->first() : null; } /** * Execute the query and get the first result or throw an exception. * * @param array $columns * @return \Illuminate\Database\Eloquent\Model|static * * @throws \Illuminate\Database\Eloquent\ModelNotFoundException */ public function firstOrFail($columns = ['*']) { if (! is_null($model = $this->first($columns))) { return $model; } throw (new ModelNotFoundException)->setModel(get_class($this->related)); } /** * Execute the query and get the first result or call a callback. * * @param \Closure|array $columns * @param \Closure|null $callback * @return \Illuminate\Database\Eloquent\Model|static|mixed */ public function firstOr($columns = ['*'], Closure $callback = null) { if ($columns instanceof Closure) { $callback = $columns; $columns = ['*']; } if (! is_null($model = $this->first($columns))) { return $model; } return $callback(); } /** * Get the results of the relationship. * * @return mixed */ public function getResults() { return ! is_null($this->parent->{$this->parentKey}) ? $this->get() : $this->related->newCollection(); } /** * Execute the query as a "select" statement. * * @param array $columns * @return \Illuminate\Database\Eloquent\Collection */ public function get($columns = ['*']) { // First we'll add the proper select columns onto the query so it is run with // the proper columns. Then, we will get the results and hydrate our pivot // models with the result of those columns as a separate model relation. $builder = $this->query->applyScopes(); $columns = $builder->getQuery()->columns ? [] : $columns; $models = $builder->addSelect( $this->shouldSelect($columns) )->getModels(); $this->hydratePivotRelation($models); // If we actually found models we will also eager load any relationships that // have been specified as needing to be eager loaded. This will solve the // n + 1 query problem for the developer and also increase performance. if (count($models) > 0) { $models = $builder->eagerLoadRelations($models); } return $this->related->newCollection($models); } /** * Get the select columns for the relation query. * * @param array $columns * @return array */ protected function shouldSelect(array $columns = ['*']) { if ($columns == ['*']) { $columns = [$this->related->getTable().'.*']; } return array_merge($columns, $this->aliasedPivotColumns()); } /** * Get the pivot columns for the relation. * * "pivot_" is prefixed ot each column for easy removal later. * * @return array */ protected function aliasedPivotColumns() { $defaults = [$this->foreignPivotKey, $this->relatedPivotKey]; return collect(array_merge($defaults, $this->pivotColumns))->map(function ($column) { return $this->qualifyPivotColumn($column).' as pivot_'.$column; })->unique()->all(); } /** * Get a paginator for the "select" statement. * * @param int|null $perPage * @param array $columns * @param string $pageName * @param int|null $page * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator */ public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null) { $this->query->addSelect($this->shouldSelect($columns)); return tap($this->query->paginate($perPage, $columns, $pageName, $page), function ($paginator) { $this->hydratePivotRelation($paginator->items()); }); } /** * Paginate the given query into a simple paginator. * * @param int|null $perPage * @param array $columns * @param string $pageName * @param int|null $page * @return \Illuminate\Contracts\Pagination\Paginator */ public function simplePaginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null) { $this->query->addSelect($this->shouldSelect($columns)); return tap($this->query->simplePaginate($perPage, $columns, $pageName, $page), function ($paginator) { $this->hydratePivotRelation($paginator->items()); }); } /** * Paginate the given query into a cursor paginator. * * @param int|null $perPage * @param array $columns * @param string $cursorName * @param string|null $cursor * @return \Illuminate\Contracts\Pagination\CursorPaginator */ public function cursorPaginate($perPage = null, $columns = ['*'], $cursorName = 'cursor', $cursor = null) { $this->query->addSelect($this->shouldSelect($columns)); return tap($this->query->cursorPaginate($perPage, $columns, $cursorName, $cursor), function ($paginator) { $this->hydratePivotRelation($paginator->items()); }); } /** * Chunk the results of the query. * * @param int $count * @param callable $callback * @return bool */ public function chunk($count, callable $callback) { return $this->prepareQueryBuilder()->chunk($count, function ($results, $page) use ($callback) { $this->hydratePivotRelation($results->all()); return $callback($results, $page); }); } /** * Chunk the results of a query by comparing numeric IDs. * * @param int $count * @param callable $callback * @param string|null $column * @param string|null $alias * @return bool */ public function chunkById($count, callable $callback, $column = null, $alias = null) { $this->prepareQueryBuilder(); $column = $column ?? $this->getRelated()->qualifyColumn( $this->getRelatedKeyName() ); $alias = $alias ?? $this->getRelatedKeyName(); return $this->query->chunkById($count, function ($results) use ($callback) { $this->hydratePivotRelation($results->all()); return $callback($results); }, $column, $alias); } /** * Execute a callback over each item while chunking. * * @param callable $callback * @param int $count * @return bool */ public function each(callable $callback, $count = 1000) { return $this->chunk($count, function ($results) use ($callback) { foreach ($results as $key => $value) { if ($callback($value, $key) === false) { return false; } } }); } /** * Query lazily, by chunks of the given size. * * @param int $chunkSize * @return \Illuminate\Support\LazyCollection */ public function lazy($chunkSize = 1000) { return $this->prepareQueryBuilder()->lazy($chunkSize)->map(function ($model) { $this->hydratePivotRelation([$model]); return $model; }); } /** * Query lazily, by chunking the results of a query by comparing IDs. * * @param int $chunkSize * @param string|null $column * @param string|null $alias * @return \Illuminate\Support\LazyCollection */ public function lazyById($chunkSize = 1000, $column = null, $alias = null) { $column = $column ?? $this->getRelated()->qualifyColumn( $this->getRelatedKeyName() ); $alias = $alias ?? $this->getRelatedKeyName(); return $this->prepareQueryBuilder()->lazyById($chunkSize, $column, $alias)->map(function ($model) { $this->hydratePivotRelation([$model]); return $model; }); } /** * Get a lazy collection for the given query. * * @return \Illuminate\Support\LazyCollection */ public function cursor() { return $this->prepareQueryBuilder()->cursor()->map(function ($model) { $this->hydratePivotRelation([$model]); return $model; }); } /** * Prepare the query builder for query execution. * * @return \Illuminate\Database\Eloquent\Builder */ protected function prepareQueryBuilder() { return $this->query->addSelect($this->shouldSelect()); } /** * Hydrate the pivot table relationship on the models. * * @param array $models * @return void */ protected function hydratePivotRelation(array $models) { // To hydrate the pivot relationship, we will just gather the pivot attributes // and create a new Pivot model, which is basically a dynamic model that we // will set the attributes, table, and connections on it so it will work. foreach ($models as $model) { $model->setRelation($this->accessor, $this->newExistingPivot( $this->migratePivotAttributes($model) )); } } /** * Get the pivot attributes from a model. * * @param \Illuminate\Database\Eloquent\Model $model * @return array */ protected function migratePivotAttributes(Model $model) { $values = []; foreach ($model->getAttributes() as $key => $value) { // To get the pivots attributes we will just take any of the attributes which // begin with "pivot_" and add those to this arrays, as well as unsetting // them from the parent's models since they exist in a different table. if (strpos($key, 'pivot_') === 0) { $values[substr($key, 6)] = $value; unset($model->$key); } } return $values; } /** * If we're touching the parent model, touch. * * @return void */ public function touchIfTouching() { if ($this->touchingParent()) { $this->getParent()->touch(); } if ($this->getParent()->touches($this->relationName)) { $this->touch(); } } /** * Determine if we should touch the parent on sync. * * @return bool */ protected function touchingParent() { return $this->getRelated()->touches($this->guessInverseRelation()); } /** * Attempt to guess the name of the inverse of the relation. * * @return string */ protected function guessInverseRelation() { return Str::camel(Str::pluralStudly(class_basename($this->getParent()))); } /** * Touch all of the related models for the relationship. * * E.g.: Touch all roles associated with this user. * * @return void */ public function touch() { $key = $this->getRelated()->getKeyName(); $columns = [ $this->related->getUpdatedAtColumn() => $this->related->freshTimestampString(), ]; // If we actually have IDs for the relation, we will run the query to update all // the related model's timestamps, to make sure these all reflect the changes // to the parent models. This will help us keep any caching synced up here. if (count($ids = $this->allRelatedIds()) > 0) { $this->getRelated()->newQueryWithoutRelationships()->whereIn($key, $ids)->update($columns); } } /** * Get all of the IDs for the related models. * * @return \Illuminate\Support\Collection */ public function allRelatedIds() { return $this->newPivotQuery()->pluck($this->relatedPivotKey); } /** * Save a new model and attach it to the parent model. * * @param \Illuminate\Database\Eloquent\Model $model * @param array $pivotAttributes * @param bool $touch * @return \Illuminate\Database\Eloquent\Model */ public function save(Model $model, array $pivotAttributes = [], $touch = true) { $model->save(['touch' => false]); $this->attach($model, $pivotAttributes, $touch); return $model; } /** * Save an array of new models and attach them to the parent model. * * @param \Illuminate\Support\Collection|array $models * @param array $pivotAttributes * @return array */ public function saveMany($models, array $pivotAttributes = []) { foreach ($models as $key => $model) { $this->save($model, (array) ($pivotAttributes[$key] ?? []), false); } $this->touchIfTouching(); return $models; } /** * Create a new instance of the related model. * * @param array $attributes * @param array $joining * @param bool $touch * @return \Illuminate\Database\Eloquent\Model */ public function create(array $attributes = [], array $joining = [], $touch = true) { $instance = $this->related->newInstance($attributes); // Once we save the related model, we need to attach it to the base model via // through intermediate table so we'll use the existing "attach" method to // accomplish this which will insert the record and any more attributes. $instance->save(['touch' => false]); $this->attach($instance, $joining, $touch); return $instance; } /** * Create an array of new instances of the related models. * * @param iterable $records * @param array $joinings * @return array */ public function createMany(iterable $records, array $joinings = []) { $instances = []; foreach ($records as $key => $record) { $instances[] = $this->create($record, (array) ($joinings[$key] ?? []), false); } $this->touchIfTouching(); return $instances; } /** * Add the constraints for a relationship query. * * @param \Illuminate\Database\Eloquent\Builder $query * @param \Illuminate\Database\Eloquent\Builder $parentQuery * @param array|mixed $columns * @return \Illuminate\Database\Eloquent\Builder */ public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*']) { if ($parentQuery->getQuery()->from == $query->getQuery()->from) { return $this->getRelationExistenceQueryForSelfJoin($query, $parentQuery, $columns); } $this->performJoin($query); return parent::getRelationExistenceQuery($query, $parentQuery, $columns); } /** * Add the constraints for a relationship query on the same table. * * @param \Illuminate\Database\Eloquent\Builder $query * @param \Illuminate\Database\Eloquent\Builder $parentQuery * @param array|mixed $columns * @return \Illuminate\Database\Eloquent\Builder */ public function getRelationExistenceQueryForSelfJoin(Builder $query, Builder $parentQuery, $columns = ['*']) { $query->select($columns); $query->from($this->related->getTable().' as '.$hash = $this->getRelationCountHash()); $this->related->setTable($hash); $this->performJoin($query); return parent::getRelationExistenceQuery($query, $parentQuery, $columns); } /** * Get the key for comparing against the parent key in "has" query. * * @return string */ public function getExistenceCompareKey() { return $this->getQualifiedForeignPivotKeyName(); } /** * Specify that the pivot table has creation and update timestamps. * * @param mixed $createdAt * @param mixed $updatedAt * @return $this */ public function withTimestamps($createdAt = null, $updatedAt = null) { $this->withTimestamps = true; $this->pivotCreatedAt = $createdAt; $this->pivotUpdatedAt = $updatedAt; return $this->withPivot($this->createdAt(), $this->updatedAt()); } /** * Get the name of the "created at" column. * * @return string */ public function createdAt() { return $this->pivotCreatedAt ?: $this->parent->getCreatedAtColumn(); } /** * Get the name of the "updated at" column. * * @return string */ public function updatedAt() { return $this->pivotUpdatedAt ?: $this->parent->getUpdatedAtColumn(); } /** * Get the foreign key for the relation. * * @return string */ public function getForeignPivotKeyName() { return $this->foreignPivotKey; } /** * Get the fully qualified foreign key for the relation. * * @return string */ public function getQualifiedForeignPivotKeyName() { return $this->qualifyPivotColumn($this->foreignPivotKey); } /** * Get the "related key" for the relation. * * @return string */ public function getRelatedPivotKeyName() { return $this->relatedPivotKey; } /** * Get the fully qualified "related key" for the relation. * * @return string */ public function getQualifiedRelatedPivotKeyName() { return $this->qualifyPivotColumn($this->relatedPivotKey); } /** * Get the parent key for the relationship. * * @return string */ public function getParentKeyName() { return $this->parentKey; } /** * Get the fully qualified parent key name for the relation. * * @return string */ public function getQualifiedParentKeyName() { return $this->parent->qualifyColumn($this->parentKey); } /** * Get the related key for the relationship. * * @return string */ public function getRelatedKeyName() { return $this->relatedKey; } /** * Get the fully qualified related key name for the relation. * * @return string */ public function getQualifiedRelatedKeyName() { return $this->related->qualifyColumn($this->relatedKey); } /** * Get the intermediate table for the relationship. * * @return string */ public function getTable() { return $this->table; } /** * Get the relationship name for the relationship. * * @return string */ public function getRelationName() { return $this->relationName; } /** * Get the name of the pivot accessor for this relationship. * * @return string */ public function getPivotAccessor() { return $this->accessor; } /** * Get the pivot columns for this relationship. * * @return array */ public function getPivotColumns() { return $this->pivotColumns; } /** * Qualify the given column name by the pivot table. * * @param string $column * @return string */ public function qualifyPivotColumn($column) { return Str::contains($column, '.') ? $column : $this->table.'.'.$column; } } HasOneOrMany.php000066600000030004150515304400007556 0ustar00localKey = $localKey; $this->foreignKey = $foreignKey; parent::__construct($query, $parent); } /** * Create and return an un-saved instance of the related model. * * @param array $attributes * @return \Illuminate\Database\Eloquent\Model */ public function make(array $attributes = []) { return tap($this->related->newInstance($attributes), function ($instance) { $this->setForeignAttributesForCreate($instance); }); } /** * Create and return an un-saved instance of the related models. * * @param iterable $records * @return \Illuminate\Database\Eloquent\Collection */ public function makeMany($records) { $instances = $this->related->newCollection(); foreach ($records as $record) { $instances->push($this->make($record)); } return $instances; } /** * Set the base constraints on the relation query. * * @return void */ public function addConstraints() { if (static::$constraints) { $query = $this->getRelationQuery(); $query->where($this->foreignKey, '=', $this->getParentKey()); $query->whereNotNull($this->foreignKey); } } /** * Set the constraints for an eager load of the relation. * * @param array $models * @return void */ public function addEagerConstraints(array $models) { $whereIn = $this->whereInMethod($this->parent, $this->localKey); $this->getRelationQuery()->{$whereIn}( $this->foreignKey, $this->getKeys($models, $this->localKey) ); } /** * Match the eagerly loaded results to their single parents. * * @param array $models * @param \Illuminate\Database\Eloquent\Collection $results * @param string $relation * @return array */ public function matchOne(array $models, Collection $results, $relation) { return $this->matchOneOrMany($models, $results, $relation, 'one'); } /** * Match the eagerly loaded results to their many parents. * * @param array $models * @param \Illuminate\Database\Eloquent\Collection $results * @param string $relation * @return array */ public function matchMany(array $models, Collection $results, $relation) { return $this->matchOneOrMany($models, $results, $relation, 'many'); } /** * Match the eagerly loaded results to their many parents. * * @param array $models * @param \Illuminate\Database\Eloquent\Collection $results * @param string $relation * @param string $type * @return array */ protected function matchOneOrMany(array $models, Collection $results, $relation, $type) { $dictionary = $this->buildDictionary($results); // Once we have the dictionary we can simply spin through the parent models to // link them up with their children using the keyed dictionary to make the // matching very convenient and easy work. Then we'll just return them. foreach ($models as $model) { if (isset($dictionary[$key = $this->getDictionaryKey($model->getAttribute($this->localKey))])) { $model->setRelation( $relation, $this->getRelationValue($dictionary, $key, $type) ); } } return $models; } /** * Get the value of a relationship by one or many type. * * @param array $dictionary * @param string $key * @param string $type * @return mixed */ protected function getRelationValue(array $dictionary, $key, $type) { $value = $dictionary[$key]; return $type === 'one' ? reset($value) : $this->related->newCollection($value); } /** * Build model dictionary keyed by the relation's foreign key. * * @param \Illuminate\Database\Eloquent\Collection $results * @return array */ protected function buildDictionary(Collection $results) { $foreign = $this->getForeignKeyName(); return $results->mapToDictionary(function ($result) use ($foreign) { return [$this->getDictionaryKey($result->{$foreign}) => $result]; })->all(); } /** * Find a model by its primary key or return a new instance of the related model. * * @param mixed $id * @param array $columns * @return \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Model */ public function findOrNew($id, $columns = ['*']) { if (is_null($instance = $this->find($id, $columns))) { $instance = $this->related->newInstance(); $this->setForeignAttributesForCreate($instance); } return $instance; } /** * Get the first related model record matching the attributes or instantiate it. * * @param array $attributes * @param array $values * @return \Illuminate\Database\Eloquent\Model */ public function firstOrNew(array $attributes = [], array $values = []) { if (is_null($instance = $this->where($attributes)->first())) { $instance = $this->related->newInstance(array_merge($attributes, $values)); $this->setForeignAttributesForCreate($instance); } return $instance; } /** * Get the first related record matching the attributes or create it. * * @param array $attributes * @param array $values * @return \Illuminate\Database\Eloquent\Model */ public function firstOrCreate(array $attributes = [], array $values = []) { if (is_null($instance = $this->where($attributes)->first())) { $instance = $this->create(array_merge($attributes, $values)); } return $instance; } /** * Create or update a related record matching the attributes, and fill it with values. * * @param array $attributes * @param array $values * @return \Illuminate\Database\Eloquent\Model */ public function updateOrCreate(array $attributes, array $values = []) { return tap($this->firstOrNew($attributes), function ($instance) use ($values) { $instance->fill($values); $instance->save(); }); } /** * Attach a model instance to the parent model. * * @param \Illuminate\Database\Eloquent\Model $model * @return \Illuminate\Database\Eloquent\Model|false */ public function save(Model $model) { $this->setForeignAttributesForCreate($model); return $model->save() ? $model : false; } /** * Attach a collection of models to the parent instance. * * @param iterable $models * @return iterable */ public function saveMany($models) { foreach ($models as $model) { $this->save($model); } return $models; } /** * Create a new instance of the related model. * * @param array $attributes * @return \Illuminate\Database\Eloquent\Model */ public function create(array $attributes = []) { return tap($this->related->newInstance($attributes), function ($instance) { $this->setForeignAttributesForCreate($instance); $instance->save(); }); } /** * Create a new instance of the related model. Allow mass-assignment. * * @param array $attributes * @return \Illuminate\Database\Eloquent\Model */ public function forceCreate(array $attributes = []) { $attributes[$this->getForeignKeyName()] = $this->getParentKey(); return $this->related->forceCreate($attributes); } /** * Create a Collection of new instances of the related model. * * @param iterable $records * @return \Illuminate\Database\Eloquent\Collection */ public function createMany(iterable $records) { $instances = $this->related->newCollection(); foreach ($records as $record) { $instances->push($this->create($record)); } return $instances; } /** * Set the foreign ID for creating a related model. * * @param \Illuminate\Database\Eloquent\Model $model * @return void */ protected function setForeignAttributesForCreate(Model $model) { $model->setAttribute($this->getForeignKeyName(), $this->getParentKey()); } /** * Add the constraints for a relationship query. * * @param \Illuminate\Database\Eloquent\Builder $query * @param \Illuminate\Database\Eloquent\Builder $parentQuery * @param array|mixed $columns * @return \Illuminate\Database\Eloquent\Builder */ public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*']) { if ($query->getQuery()->from == $parentQuery->getQuery()->from) { return $this->getRelationExistenceQueryForSelfRelation($query, $parentQuery, $columns); } return parent::getRelationExistenceQuery($query, $parentQuery, $columns); } /** * Add the constraints for a relationship query on the same table. * * @param \Illuminate\Database\Eloquent\Builder $query * @param \Illuminate\Database\Eloquent\Builder $parentQuery * @param array|mixed $columns * @return \Illuminate\Database\Eloquent\Builder */ public function getRelationExistenceQueryForSelfRelation(Builder $query, Builder $parentQuery, $columns = ['*']) { $query->from($query->getModel()->getTable().' as '.$hash = $this->getRelationCountHash()); $query->getModel()->setTable($hash); return $query->select($columns)->whereColumn( $this->getQualifiedParentKeyName(), '=', $hash.'.'.$this->getForeignKeyName() ); } /** * Get the key for comparing against the parent key in "has" query. * * @return string */ public function getExistenceCompareKey() { return $this->getQualifiedForeignKeyName(); } /** * Get the key value of the parent's local key. * * @return mixed */ public function getParentKey() { return $this->parent->getAttribute($this->localKey); } /** * Get the fully qualified parent key name. * * @return string */ public function getQualifiedParentKeyName() { return $this->parent->qualifyColumn($this->localKey); } /** * Get the plain foreign key. * * @return string */ public function getForeignKeyName() { $segments = explode('.', $this->getQualifiedForeignKeyName()); return end($segments); } /** * Get the foreign key for the relationship. * * @return string */ public function getQualifiedForeignKeyName() { return $this->foreignKey; } /** * Get the local key for the relationship. * * @return string */ public function getLocalKeyName() { return $this->localKey; } } HasOneThrough.php000066600000004316150515304400010000 0ustar00first() ?: $this->getDefaultFor($this->farParent); } /** * Initialize the relation on a set of models. * * @param array $models * @param string $relation * @return array */ public function initRelation(array $models, $relation) { foreach ($models as $model) { $model->setRelation($relation, $this->getDefaultFor($model)); } return $models; } /** * Match the eagerly loaded results to their parents. * * @param array $models * @param \Illuminate\Database\Eloquent\Collection $results * @param string $relation * @return array */ public function match(array $models, Collection $results, $relation) { $dictionary = $this->buildDictionary($results); // Once we have the dictionary we can simply spin through the parent models to // link them up with their children using the keyed dictionary to make the // matching very convenient and easy work. Then we'll just return them. foreach ($models as $model) { if (isset($dictionary[$key = $this->getDictionaryKey($model->getAttribute($this->localKey))])) { $value = $dictionary[$key]; $model->setRelation( $relation, reset($value) ); } } return $models; } /** * Make a new related instance for the given model. * * @param \Illuminate\Database\Eloquent\Model $parent * @return \Illuminate\Database\Eloquent\Model */ public function newRelatedInstanceFor(Model $parent) { return $this->related->newInstance(); } } HasMany.php000066600000002225150515304400006617 0ustar00getParentKey()) ? $this->query->get() : $this->related->newCollection(); } /** * Initialize the relation on a set of models. * * @param array $models * @param string $relation * @return array */ public function initRelation(array $models, $relation) { foreach ($models as $model) { $model->setRelation($relation, $this->related->newCollection()); } return $models; } /** * Match the eagerly loaded results to their parents. * * @param array $models * @param \Illuminate\Database\Eloquent\Collection $results * @param string $relation * @return array */ public function match(array $models, Collection $results, $relation) { return $this->matchMany($models, $results, $relation); } } MorphMany.php000066600000003006150515304400007167 0ustar00getParentKey()) ? $this->query->get() : $this->related->newCollection(); } /** * Initialize the relation on a set of models. * * @param array $models * @param string $relation * @return array */ public function initRelation(array $models, $relation) { foreach ($models as $model) { $model->setRelation($relation, $this->related->newCollection()); } return $models; } /** * Match the eagerly loaded results to their parents. * * @param array $models * @param \Illuminate\Database\Eloquent\Collection $results * @param string $relation * @return array */ public function match(array $models, Collection $results, $relation) { return $this->matchMany($models, $results, $relation); } /** * Create a new instance of the related model. Allow mass-assignment. * * @param array $attributes * @return \Illuminate\Database\Eloquent\Model */ public function forceCreate(array $attributes = []) { $attributes[$this->getMorphType()] = $this->morphClass; return parent::forceCreate($attributes); } }