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

added whereBelongsTo methods in where section of query builder docs introduced in Laravel 8.63.0. #7334

Closed
wants to merge 1 commit into from
Closed
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
20 changes: 20 additions & 0 deletions queries.md
Original file line number Diff line number Diff line change
Expand Up @@ -595,6 +595,26 @@ You may also pass an array of column comparisons to the `whereColumn` method. Th
['updated_at', '>', 'created_at'],
])->get();

**whereBelongsTo**

When retrieving `belongsTo` related records, you can usually use the inverse (hasMany) of the relationship, like so:

$author->posts()

However, sometimes this is not possible, and you must filter an existing query by its parent record:

$query->where('author_id', $author->id)

This works, but explicitly depends on the name of foreign key (`author_id`), and the name of the owner key (`id`) in most cases. This is a maintenance burden, as these key names can be changed inside the relationship method and will subsequently become outdated across your entire app. So query builder has `whereBelongsTo`. You may use it like so:

$query->whereBelongsTo($author)

It will automatically retrieve the foreign key name from the relationship (`author`), and the correct owner key from the related model (`$author`).

Sometimes, this is not appropriate. If the `$author` is an instance of `App\Models\User`, `whereBelongsTo()` will search for a `user()` relationship that does not exist. In this case, you may manually specify the relationship name:

$query->whereBelongsTo($author, 'author')

<a name="logical-grouping"></a>
### Logical Grouping

Expand Down