You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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 */publicfunctionwithout($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;
}
The text was updated successfully, but these errors were encountered:
@dalabarge , try to send a PR. Take not that you should handle nested relations as the function you posted here does not.
GrahamCampbell
changed the title
[Proposal] Add a Builder::without() method to unset $eagerLoads
Add a Builder::without() method to unset $eagerLoads
Dec 29, 2014
Pretty straight forward, but I ran into a problem with eager loaded relationships. I had set up a
User
model theUser::$with
property to always include aName
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 theUser
is needed and querying with the eager loadedName
relationship causes excessive, unnecessary queries (as I'm not concerned with theName
attributes). So a solution was:So why not just add this as
Builder::without()
method that removes the unneeded relationships that might have been set up on theModel::$with
or merged previously using theBuilder::with()
method? Here's an example of such a method:The text was updated successfully, but these errors were encountered: