laravel 直接从模型实例化查询构建器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33908625/
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:44:21  来源:igfitidea点击:

Instance the query builder directly from model

laravelmodeleloquent

提问by David Rodrigues

When I do something like SomeModel::with('user')it returns a Query\Builderinstance. How can I get this instance without need call the with()(or similar)?

当我做类似的事情时,SomeModel::with('user')它会返回一个Query\Builder实例。我怎样才能在不需要调用with()或类似的)的情况下获得这个实例?

For instance, I tried it: new SomeModel, but it'll returns obviously the instance of my model, not the query builder (not worked to me). The SomeModel::getQuerynot works too, because it returns a Query\Buildernot related to my model.

例如,我尝试了它:new SomeModel,但它显然会返回我的模型的实例,而不是查询构建器(对我不起作用)。也SomeModel::getQuery不起作用,因为它返回一个Query\Builder与我的模型无关的。

I need it to I setup based on some conditionals. So initially it need be empty, like it:

我需要它根据一些条件进行设置。所以最初它需要是empty,像这样:

$someBuilder = SomeModel::getQueryBuilder(); // eg.

if(condition()) {
    $someBuilder->where(...);
}

$someResults = $someBuilder->get();

回答by Joseph Silber

Use the static querymethod:

使用静态query方法:

$query = User::query();


Additionally, you can use the whenmethod to chain these conditionals directly onto the query builder itself:

此外,您可以使用该when方法将这些条件直接链接到查询构建器本身:

$results = SomeModel::query()->when(condition(), function ($query) {
    $query->where(...);
})->get();

This is functionally equivalent to the imperative ifclause.

这在功能上等同于祈使if句。