Disable eager relations

痞子三分冷 提交于 2020-01-01 04:07:08

问题


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.

  1. Create scope in your default model class:

    public function scopeNoEagerLoads($query){
        return $query->setEagerLoads([]);
    }
    
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!