Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(); 
like image 622
David Rodrigues Avatar asked Nov 25 '15 04:11

David Rodrigues


People also ask

What is difference between eloquent and query builder?

Eloquent ORM is best suited working with fewer data in a particular table. On the other side, query builder takes less time to handle numerous data whether in one or more tables faster than Eloquent ORM. In my case, I use ELoquent ORM in an application with tables that will hold less than 17500 entries.

What is database query builder?

The database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application, and works on all supported database systems.

What is eloquent builder?

Laravel eloquent provides a simple way of making database queries in your application. It uses Models as an object to interact with a table. To fetch all records from a table you can simple use. Post::get();


1 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.

like image 156
Joseph Silber Avatar answered Sep 21 '22 22:09

Joseph Silber