Skip to content

Commit

Permalink
[8.x] Add nested relationships to whereRelation function (laravel#39064)
Browse files Browse the repository at this point in the history
* Add nested relationships to whereRelation function

* Removed 2 spaces

* formatting

* Update QueriesRelationships.php

Co-authored-by: Jose María Gómez Martín <[email protected]>
Co-authored-by: Taylor Otwell <[email protected]>
  • Loading branch information
3 people authored Oct 6, 2021
1 parent f0acffe commit bc92a96
Showing 1 changed file with 34 additions and 6 deletions.
40 changes: 34 additions & 6 deletions src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php
Original file line number Diff line number Diff line change
Expand Up @@ -362,9 +362,23 @@ public function orWhereDoesntHaveMorph($relation, $types, Closure $callback = nu
*/
public function whereRelation($relation, $column, $operator = null, $value = null)
{
return $this->whereHas($relation, function ($query) use ($column, $operator, $value) {
$query->where($column, $operator, $value);
});
$relations = collect(explode('.', $relation));

return $this->when(
$relations->count() == 1,
function($query) use ($relations, $column, $operator, $value) {
$query->whereHas($relations->first(), function ($query) use ($column, $operator, $value) {
$query->where($column, $operator, $value);
});
},
function($query) use ($relations, $column, $operator, $value) {
$query->whereHas($relations->first(), function ($query) use ($relations, $column, $operator, $value) {
$relations->shift();

$query->whereRelation($relations->implode('.'), $column, $operator, $value);
});
}
);
}

/**
Expand All @@ -378,9 +392,23 @@ public function whereRelation($relation, $column, $operator = null, $value = nul
*/
public function orWhereRelation($relation, $column, $operator = null, $value = null)
{
return $this->orWhereHas($relation, function ($query) use ($column, $operator, $value) {
$query->where($column, $operator, $value);
});
$relations = collect(explode('.', $relation));

return $this->when(
$relations->count() == 1,
function($query) use ($relations, $column, $operator, $value) {
$query->orWhereHas($relations->first(), function ($query) use ($column, $operator, $value) {
$query->where($column, $operator, $value);
});
},
function($query) use ($relations, $column, $operator, $value) {
$query->orWhereHas($relations->first(), function ($query) use ($relations, $column, $operator, $value) {
$relations->shift();

$query->orWhereRelation($relations->implode('.'), $column, $operator, $value);
});
}
);
}

/**
Expand Down

0 comments on commit bc92a96

Please sign in to comment.