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

[8.x] Add withExists method to QueriesRelationships #37295

Closed
wants to merge 1 commit into from
Closed

[8.x] Add withExists method to QueriesRelationships #37295

wants to merge 1 commit into from

Conversation

bastien-phi
Copy link
Contributor

This PR adds withExists method to QueriesRelationships.

If we want to list our Users with an extra columns is_author (based on the fact that the user wrote a Post), at the moment we can only do something like

$users = User::withCount('posts')->get();
//...
$isAuthor = $user->posts_count > 0;

It works but it is not very efficient as the database needs to count every posts whereas we only need to know if there is at least one of them.

With this PR, we could simply do an existence check with sql exists wich is more efficient

$users = User::withExists('posts')->get();
//...
$isAuthor = $user->posts_exists;

The column name can also be aliased

$users = User::withExists('posts as is_author')->get();
//...
$isAuthor = $user->is_author;

Relations can be filtered and multiple relation existences can be fetched at the same time :

$users = User::withExists([
        'posts as is_author',
        'posts as is_tech_author' => function ($query) {
            return $query->where('category', 'tech');
        },
        'comments',
    ])->get();
//...
$user->is_author;
$user->is_tech_author;
$user->comments_exists;

In a future PR we could add loadExists for both Model and Illuminate\Database\Eloquent\Collection

@taylorotwell
Copy link
Member

Thanks for your pull request to Laravel!

Unfortunately, I'm going to delay merging this code for now. To preserve our ability to adequately maintain the framework, we need to be very careful regarding the amount of code we include.

If possible, please consider releasing your code as a package so that the community can still take advantage of your contributions!

If you feel absolutely certain that this code corrects a bug in the framework, please "@" mention me in a follow-up comment with further explanation so that GitHub will send me a notification of your response.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants