master

laravel/framework

Last updated at: 29/12/2023 09:22

HasMany.php

TLDR

The HasMany.php file is a part of the Illuminate\Database\Eloquent\Relations namespace and contains the HasMany class. This class is used to define a one-to-many relationship in Laravel's Eloquent ORM.

Methods

one

Converts the HasMany relationship to a "has one" relationship. Returns an instance of the HasOne class.

getResults

Gets the results of the relationship. If the parent key is not null, it fetches the results using the query builder's get method. Otherwise, it creates and returns a new collection of the related model.

initRelation

Initializes the relationship on a set of models. It sets the relation on each model to a new collection of related models.

match

Matches the eagerly loaded results to their parent models. It calls the matchMany method to perform the matching.

Classes

HasMany

The HasMany class extends the HasOneOrMany class and is used to define a one-to-many relationship in Laravel's Eloquent ORM. It provides methods to convert the relationship to a "has one" relationship, get the relationship results, initialize the relationship on models, and match eagerly loaded results to their parent models.

<?php

namespace Illuminate\Database\Eloquent\Relations;

use Illuminate\Database\Eloquent\Collection;

class HasMany extends HasOneOrMany
{
    /**
     * Convert the relationship to a "has one" relationship.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function one()
    {
        return HasOne::noConstraints(fn () => new HasOne(
            $this->getQuery(),
            $this->parent,
            $this->foreignKey,
            $this->localKey
        ));
    }

    /**
     * Get the results of the relationship.
     *
     * @return mixed
     */
    public function getResults()
    {
        return ! is_null($this->getParentKey())
                ? $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);
    }
}