Disable eager relations
17,166
Solution 1
If you have to set the $with
property on your model rather than leaving it empty, you can manually override the relationships that need to be eager loaded like this:
Model::setEagerLoads([])->get();
Solution 2
In addition to Thomas Kim answer.
If you anyway extend Eloquent\Model class and often need to strip off relations from model, this solution might suit you well.
-
Create scope in your default model class:
public function scopeNoEagerLoads($query){ return $query->setEagerLoads([]); }
-
For any ORM, that extends that class you will be able to:
User::noEagerLoads()->all()
Solution 3
Just like the issues say
Model::without(['countries', 'roles' ])->all();
Related videos on Youtube
Author by
Yauheni Prakopchyk
Updated on September 14, 2022Comments
-
Yauheni Prakopchyk over 1 year
In my project I have many Eloquent models that have eager relations configured in class like this:
protected $with = [ 'countries', 'roles' ];
But sometimes I need just old plain model without any relations. Can I somehow do:
Model::noRelations()->all()
Really don't wanna use query builder nor create another class just for few occasions.
-
Yauheni Prakopchyk over 8 yearsWorks like a charm! Exactly what I need.
-
BlackBurn027 over 6 yearsHow can i implement this if This Model is being referred in relation of other Model something like ModelTwo::with('modelOne')->get(); how to avoid eager loading for modelOne then ?
-
Ahmed Aboud about 3 years@BlackBurn027 i guess this should work ModelTwo::with(['modelOne' => function ($query) { $query->setEagerLoads([]); }]