getRelation() public method

Get the relation instance for the given relation name.
public getRelation ( string $name ) : Illuminate\Database\Eloquent\Relations\Relation
$name string
return Illuminate\Database\Eloquent\Relations\Relation
Exemplo n.º 1
0
 /**
  * Get queries to fetch relationships.
  *
  * @param  Builder  $builder
  * @param  array    $models
  * @param  string   $name
  * @param  Closure  $constraints
  * @return array
  */
 protected function getQueries(Builder $builder, array $models, $name, Closure $constraints)
 {
     return collect($models)->map(function ($model) use($builder, $name, $constraints) {
         $relation = $builder->getRelation($name);
         $relation->addEagerConstraints([$model]);
         call_user_func_array($constraints, [$relation, $model]);
         if (method_exists($relation, 'getSelectColumns')) {
             $r = new ReflectionMethod(get_class($relation), 'getSelectColumns');
             $r->setAccessible(true);
             $select = $r->invoke($relation, ['*']);
             $relation->addSelect($select);
         }
         $relation->initRelation([$model], $name);
         return $relation;
     });
 }
Exemplo n.º 2
0
 /**
  * Get the relation instance for the given relation name.
  *
  * @param  string $relation
  *
  * @return Relation
  * @throws BadRequestException
  */
 public function getRelation($relation)
 {
     $query = Relation::noConstraints(function () use($relation) {
         /** @var BaseModel $model */
         $model = $this->getModel();
         $relationType = $model->getReferencingType($relation);
         if (RelationSchema::HAS_MANY === $relationType) {
             return $model->getHasManyByRelationName($relation);
         } elseif (RelationSchema::MANY_MANY === $relationType) {
             return $model->getBelongsToManyByRelationName($relation);
         } elseif (RelationSchema::BELONGS_TO === $relationType) {
             return $model->getBelongsToByRelationName($relation);
         }
         return null;
     });
     if (!empty($query)) {
         return $query;
     }
     if (!method_exists($this->getModel(), $relation)) {
         throw new BadRequestException('Unknown relationship: ' . $relation);
     }
     return parent::getRelation($relation);
 }