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

Add a Builder::without() method to unset $eagerLoads #5590

Closed
dalabarge opened this issue Aug 28, 2014 · 2 comments
Closed

Add a Builder::without() method to unset $eagerLoads #5590

dalabarge opened this issue Aug 28, 2014 · 2 comments

Comments

@dalabarge
Copy link
Contributor

Pretty straight forward, but I ran into a problem with eager loaded relationships. I had set up a User model the User::$with property to always include a Name model relationship. This fit 90% of the use cases so it made sense vs. adding it manually on each query. Now, however, I have a use case where the User is needed and querying with the eager loaded Name relationship causes excessive, unnecessary queries (as I'm not concerned with the Name attributes). So a solution was:

// Reset the builder to remove the eager loaded Name relationship
$builder = $foo->users();
$relationships = $builder->getEagerLoads();
unset($relationships['name']);
$builder->setEagerLoads($relationships);

// Continue with query like normal but this time without the eager loaded Name relationship
$users = $builder->where(...)->get();

So why not just add this as Builder::without() method that removes the unneeded relationships that might have been set up on the Model::$with or merged previously using the Builder::with() method? Here's an example of such a method:

/**
 * Unset the relationships that should not be eager loaded.
 *
 * @param  mixed  $relations
 * @return $this
 */
public function without($relations)
{
    if (is_string($relations)) $relations = func_get_args();

    $eagers = array_diff(array_keys($this->eagerLoad), $relations);
    $this->eagerLoad = array_only($this->eagerLoad, $eagers);

    return $this;
}
@ibrasho
Copy link
Contributor

ibrasho commented Dec 27, 2014

@dalabarge , try to send a PR. Take not that you should handle nested relations as the function you posted here does not.

@GrahamCampbell GrahamCampbell changed the title [Proposal] Add a Builder::without() method to unset $eagerLoads Add a Builder::without() method to unset $eagerLoads Dec 29, 2014
@GrahamCampbell
Copy link
Member

We're open to pull requests.

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

No branches or pull requests

3 participants