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

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

本文介绍了直接从模型实例化查询构建器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我做类似SomeModel::with('user')的操作时,它返回一个Query\Builder实例.

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)?

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

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.

我需要根据一些条件进行设置.因此,一开始它必须是 empty ,像这样:

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

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

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

$someResults = $someBuilder->get();

推荐答案

使用静态query方法:

$query = User::query();


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


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

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

这在功能上等同于命令式if子句.

This is functionally equivalent to the imperative if clause.

这篇关于直接从模型实例化查询构建器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 15:11