Instance the query builder directly from model

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

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.

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();

Answers


Use the static query method:

$query = User::query();

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();

This is functionally equivalent to the imperative if clause.


Need Your Help

Combo box with multiple columns and related values

asp.net ajax vb.net drop-down-menu telerik

Is it possible to show multiple columns and headers inside of a combo box/dropdown list in asp.net and show related columns values, for an example, if I click on a country name then it should show ...

How to disable resizable property of textarea?

html css

I want to disable the resizable property of a textarea.