Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[11.x] Eloquent inverse relations #51582

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
<?php

namespace Illuminate\Database\Eloquent\Relations\Concerns;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\RelationNotFoundException;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;

trait SupportsInverseRelations
{
/**
* The name of the inverse relationship.
*
* @var string|null
*/
protected string|null $inverseRelationship = null;

/**
* Instruct Eloquent to link the related models back to the parent after the relationship query has run.
*
* Alias of "chaperone".
*
* @param string|null $relation
* @return $this
*/
public function inverse(?string $relation = null)
{
return $this->chaperone($relation);
}

/**
* Instruct Eloquent to link the related models back to the parent after the relationship query has run.
*
* @param string|null $relation
* @return $this
*/
public function chaperone(?string $relation = null)
{
$relation ??= $this->guessInverseRelation();

if (! $relation || ! $this->getModel()->isRelation($relation)) {
throw RelationNotFoundException::make($this->getModel(), $relation ?: 'null');
}

if ($this->inverseRelationship === null && $relation) {
$this->query->afterQuery(function ($result) {
return $this->inverseRelationship
? $this->applyInverseRelationToCollection($result, $this->getParent())
: $result;
});
}

$this->inverseRelationship = $relation;

return $this;
}

/**
* Guess the name of the inverse relationship.
*
* @return string|null
*/
protected function guessInverseRelation(): string|null
{
return Arr::first(
$this->getPossibleInverseRelations(),
fn ($relation) => $relation && $this->getModel()->isRelation($relation)
);
}

/**
* Get the possible inverse relations for the parent model.
*
* @return array<non-empty-string>
*/
protected function getPossibleInverseRelations(): array
{
return array_filter(array_unique([
Str::camel(Str::beforeLast($this->getForeignKeyName(), $this->getParent()->getKeyName())),
Str::camel(Str::beforeLast($this->getParent()->getForeignKey(), $this->getParent()->getKeyName())),
Str::camel(class_basename($this->getParent())),
'owner',
get_class($this->getParent()) === get_class($this->getModel()) ? 'parent' : null,
]));
}

/**
* Set the inverse relation on all models in a collection.
*
* @param \Illuminate\Database\Eloquent\Collection $models
* @param \Illuminate\Database\Eloquent\Model|null $parent
* @return \Illuminate\Database\Eloquent\Collection
*/
protected function applyInverseRelationToCollection($models, ?Model $parent = null)
{
$parent ??= $this->getParent();

foreach ($models as $model) {
$this->applyInverseRelationToModel($model, $parent);
}

return $models;
}

/**
* Set the inverse relation on a model.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param \Illuminate\Database\Eloquent\Model|null $parent
* @return \Illuminate\Database\Eloquent\Model
*/
protected function applyInverseRelationToModel(Model $model, ?Model $parent = null)
{
if ($inverse = $this->getInverseRelationship()) {
$parent ??= $this->getParent();

$model->setRelation($inverse, $parent);
}

return $model;
}

/**
* Get the name of the inverse relationship.
*
* @return string|null
*/
public function getInverseRelationship()
{
return $this->inverseRelationship;
}

/**
* Remove the chaperone / inverse relationship for this query.
*
* Alias of "withoutChaperone".
*
* @return $this
*/
public function withoutInverse()
{
return $this->withoutChaperone();
}

/**
* Remove the chaperone / inverse relationship for this query.
*
* @return $this
*/
public function withoutChaperone()
{
$this->inverseRelationship = null;

return $this;
}
}
17 changes: 12 additions & 5 deletions src/Illuminate/Database/Eloquent/Relations/HasMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,18 @@ class HasMany extends HasOneOrMany
*/
public function one()
{
return HasOne::noConstraints(fn () => new HasOne(
$this->getQuery(),
$this->parent,
$this->foreignKey,
$this->localKey
return HasOne::noConstraints(fn () => tap(
new HasOne(
$this->getQuery(),
$this->parent,
$this->foreignKey,
$this->localKey
),
function ($hasOne) {
if ($inverse = $this->getInverseRelationship()) {
$hasOne->inverse($inverse);
}
}
));
}

Expand Down
7 changes: 4 additions & 3 deletions src/Illuminate/Database/Eloquent/Relations/HasOne.php
Original file line number Diff line number Diff line change
Expand Up @@ -119,9 +119,10 @@ public function addOneOfManyJoinSubQueryConstraints(JoinClause $join)
*/
public function newRelatedInstanceFor(Model $parent)
{
return $this->related->newInstance()->setAttribute(
$this->getForeignKeyName(), $parent->{$this->localKey}
);
return tap($this->related->newInstance(), function ($instance) use ($parent) {
$instance->setAttribute($this->getForeignKeyName(), $parent->{$this->localKey});
$this->applyInverseRelationToModel($instance, $parent);
});
}

/**
Expand Down
20 changes: 15 additions & 5 deletions src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Concerns\InteractsWithDictionary;
use Illuminate\Database\Eloquent\Relations\Concerns\SupportsInverseRelations;
use Illuminate\Database\UniqueConstraintViolationException;

abstract class HasOneOrMany extends Relation
{
use InteractsWithDictionary;
use InteractsWithDictionary, SupportsInverseRelations;

/**
* The foreign key of the parent model.
Expand Down Expand Up @@ -53,6 +54,7 @@ public function make(array $attributes = [])
{
return tap($this->related->newInstance($attributes), function ($instance) {
$this->setForeignAttributesForCreate($instance);
$this->applyInverseRelationToModel($instance);
});
}

Expand Down Expand Up @@ -151,9 +153,13 @@ protected function matchOneOrMany(array $models, Collection $results, $relation,
// 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)
);
$related = $this->getRelationValue($dictionary, $key, $type);
$model->setRelation($relation, $related);

// Apply the inverse relation if we have one...
$type === 'one'
? $this->applyInverseRelationToModel($related, $model)
: $this->applyInverseRelationToCollection($related, $model);
}
}

Expand Down Expand Up @@ -340,6 +346,8 @@ public function create(array $attributes = [])
$this->setForeignAttributesForCreate($instance);

$instance->save();

$this->applyInverseRelationToModel($instance);
});
}

Expand All @@ -364,7 +372,7 @@ public function forceCreate(array $attributes = [])
{
$attributes[$this->getForeignKeyName()] = $this->getParentKey();

return $this->related->forceCreate($attributes);
return $this->applyInverseRelationToModel($this->related->forceCreate($attributes));
}

/**
Expand Down Expand Up @@ -415,6 +423,8 @@ public function createManyQuietly(iterable $records)
protected function setForeignAttributesForCreate(Model $model)
{
$model->setAttribute($this->getForeignKeyName(), $this->getParentKey());

$this->applyInverseRelationToModel($model);
}

/**
Expand Down
19 changes: 13 additions & 6 deletions src/Illuminate/Database/Eloquent/Relations/MorphMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,19 @@ class MorphMany extends MorphOneOrMany
*/
public function one()
{
return MorphOne::noConstraints(fn () => new MorphOne(
$this->getQuery(),
$this->getParent(),
$this->morphType,
$this->foreignKey,
$this->localKey
return MorphOne::noConstraints(fn () => tap(
new MorphOne(
$this->getQuery(),
$this->getParent(),
$this->morphType,
$this->foreignKey,
$this->localKey
),
function ($morphOne) {
if ($inverse = $this->getInverseRelationship()) {
$morphOne->inverse($inverse);
}
}
));
}

Expand Down
9 changes: 6 additions & 3 deletions src/Illuminate/Database/Eloquent/Relations/MorphOne.php
Original file line number Diff line number Diff line change
Expand Up @@ -119,9 +119,12 @@ public function addOneOfManyJoinSubQueryConstraints(JoinClause $join)
*/
public function newRelatedInstanceFor(Model $parent)
{
return $this->related->newInstance()
->setAttribute($this->getForeignKeyName(), $parent->{$this->localKey})
->setAttribute($this->getMorphType(), $this->morphClass);
return tap($this->related->newInstance(), function ($instance) use ($parent) {
$instance->setAttribute($this->getForeignKeyName(), $parent->{$this->localKey})
->setAttribute($this->getMorphType(), $this->morphClass);

$this->applyInverseRelationToModel($instance, $parent);
});
}

/**
Expand Down
18 changes: 17 additions & 1 deletion src/Illuminate/Database/Eloquent/Relations/MorphOneOrMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

abstract class MorphOneOrMany extends HasOneOrMany
{
Expand Down Expand Up @@ -78,7 +79,7 @@ public function forceCreate(array $attributes = [])
$attributes[$this->getForeignKeyName()] = $this->getParentKey();
$attributes[$this->getMorphType()] = $this->morphClass;

return $this->related->forceCreate($attributes);
return $this->applyInverseRelationToModel($this->related->forceCreate($attributes));
}

/**
Expand All @@ -92,6 +93,8 @@ protected function setForeignAttributesForCreate(Model $model)
$model->{$this->getForeignKeyName()} = $this->getParentKey();

$model->{$this->getMorphType()} = $this->morphClass;

$this->applyInverseRelationToModel($model);
}

/**
Expand Down Expand Up @@ -138,4 +141,17 @@ public function getMorphClass()
{
return $this->morphClass;
}

/**
* Get the possible inverse relations for the parent model.
*
* @return array<non-empty-string>
*/
protected function getPossibleInverseRelations(): array
{
return array_unique([
Str::beforeLast($this->getMorphType(), '_type'),
...parent::getPossibleInverseRelations(),
]);
}
}
Loading