laravel 禁用急切关系

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34052056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:45:50  来源:igfitidea点击:

Disable eager relations

laraveleloquenteager-loading

提问by Yauheni Prakopchyk

In my project I have many Eloquent models that have eager relations configured in class like this:

在我的项目中,我有许多 Eloquent 模型,它们在类中配置了热切关系,如下所示:

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.

真的不想使用查询构建器,也不想只在少数情况下创建另一个类。

回答by Thomas Kim

If you have to set the $withproperty on your model rather than leaving it empty, you can manually override the relationships that need to be eager loaded like this:

如果您必须$with在模型上设置属性而不是将其留空,您可以手动覆盖需要预先加载的关系,如下所示:

Model::setEagerLoads([])->get();

Link to API for setEagerLoads

链接到 API setEagerLoads

回答by Yauheni Prakopchyk

In addition to Thomas Kim answer.

除了 Thomas Kim 的回答。

If you anyway extend Eloquent\Model class and often need to strip off relations from model, this solution might suit you well.

如果您无论如何扩展 Eloquent\Model 类并且经常需要从模型中剥离关系,那么这个解决方案可能很适合您。

  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()
    
  1. 在您的默认模型类中创建范围:

    public function scopeNoEagerLoads($query){
        return $query->setEagerLoads([]);
    }
    
  2. 对于任何扩展该类的 ORM,您将能够:

    User::noEagerLoads()->all()
    

回答by nick huang

Just like the issuessay

就像问题所说的

Model::without(['countries', 'roles' ])->all();