Skip to content

Commit

Permalink
[10.x] Add getForeignKeyFrom method (#47378)
Browse files Browse the repository at this point in the history
* [10.x] Add getForeignKeyFrom method

* fix comment
  • Loading branch information
iamgergo authored Jun 8, 2023
1 parent 97ab967 commit 697345b
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions src/Illuminate/Database/Eloquent/Relations/BelongsTo.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public function __construct(Builder $query, Model $child, $foreignKey, $ownerKey
*/
public function getResults()
{
if (is_null($this->child->{$this->foreignKey})) {
if (is_null($this->getForeignKeyFrom($this->child))) {
return $this->getDefaultFor($this->parent);
}

Expand All @@ -94,7 +94,7 @@ public function addConstraints()
// 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});
$this->query->where($table.'.'.$this->ownerKey, '=', $this->getForeignKeyFrom($this->child));
}
}

Expand Down Expand Up @@ -130,7 +130,7 @@ protected function getEagerModelKeys(array $models)
// 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})) {
if (! is_null($value = $this->getForeignKeyFrom($model))) {
$keys[] = $value;
}
}
Expand Down Expand Up @@ -337,7 +337,7 @@ public function getQualifiedForeignKeyName()
*/
public function getParentKey()
{
return $this->child->{$this->foreignKey};
return $this->getForeignKeyFrom($this->child);
}

/**
Expand Down Expand Up @@ -371,6 +371,17 @@ protected function getRelatedKeyFrom(Model $model)
return $model->{$this->ownerKey};
}

/**
* Get the value of the model's foreign key.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @return mixed
*/
protected function getForeignKeyFrom(Model $model)
{
return $model->{$this->foreignKey};
}

/**
* Get the name of the relationship.
*
Expand Down

0 comments on commit 697345b

Please sign in to comment.