问题
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.
回答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();
Link to API for setEagerLoads
回答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()
回答3:
Just like the issues say
Model::without(['countries', 'roles' ])->all();
来源:https://stackoverflow.com/questions/34052056/disable-eager-relations