123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424 |
- <?php
-
- namespace Illuminate\Database\Eloquent\Relations;
-
- use Illuminate\Database\Eloquent\Model;
- use Illuminate\Database\Eloquent\Builder;
- use Illuminate\Database\Eloquent\Collection;
-
- abstract class HasOneOrMany extends Relation
- {
- /**
- * The foreign key of the parent model.
- *
- * @var string
- */
- protected $foreignKey;
-
- /**
- * The local key of the parent model.
- *
- * @var string
- */
- protected $localKey;
-
- /**
- * The count of self joins.
- *
- * @var int
- */
- protected static $selfJoinCount = 0;
-
- /**
- * Create a new has one or many relationship instance.
- *
- * @param \Illuminate\Database\Eloquent\Builder $query
- * @param \Illuminate\Database\Eloquent\Model $parent
- * @param string $foreignKey
- * @param string $localKey
- * @return void
- */
- public function __construct(Builder $query, Model $parent, $foreignKey, $localKey)
- {
- $this->localKey = $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);
- });
- }
-
- /**
- * Set the base constraints on the relation query.
- *
- * @return void
- */
- public function addConstraints()
- {
- if (static::$constraints) {
- $this->query->where($this->foreignKey, '=', $this->getParentKey());
-
- $this->query->whereNotNull($this->foreignKey);
- }
- }
-
- /**
- * Set the constraints for an eager load of the relation.
- *
- * @param array $models
- * @return void
- */
- public function addEagerConstraints(array $models)
- {
- $this->query->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 = $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 [$result->{$foreign} => $result];
- })->all();
- }
-
- /**
- * Find a model by its primary key or return 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($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($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 \Traversable|array $models
- * @return \Traversable|array
- */
- 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 Collection of new instances of the related model.
- *
- * @param array $records
- * @return \Illuminate\Database\Eloquent\Collection
- */
- public function createMany(array $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());
- }
-
- /**
- * Perform an update on all the related models.
- *
- * @param array $attributes
- * @return int
- */
- public function update(array $attributes)
- {
- if ($this->related->usesTimestamps() && ! is_null($this->relatedUpdatedAt())) {
- $attributes[$this->relatedUpdatedAt()] = $this->related->freshTimestampString();
- }
-
- return $this->query->update($attributes);
- }
-
- /**
- * 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 a relationship join table hash.
- *
- * @return string
- */
- public function getRelationCountHash()
- {
- return 'laravel_reserved_'.static::$selfJoinCount++;
- }
-
- /**
- * 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;
- }
- }
|