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
Instance the query builder directly from model
提问by David Rodrigues
When I do something like SomeModel::with('user')
it returns a Query\Builder
instance. 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::getQuery
not works too, because it returns a Query\Builder
not 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 query
method:
使用静态query
方法:
$query = User::query();
Additionally, you can use the when
method 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 if
clause.
这在功能上等同于祈使if
句。