NewQuery () in Laravel

What is the difference:

$model = User::newQuery(); $model->published(1); $model->get(); 

and

 $model = User; $model = $model->published(1); $model = $model->get(); 

I know that in the second example you need to assign a model callback. But is there a difference in them?

Notice, I do not cling, as there will be some conditions between checking whether to publish or not, etc.

+5
source share
1 answer

It depends on what is posted (). Changing the code a bit:

 $model = User::newQuery(); $model->where('published', 1); $model->get(); 

or

 $model = new User; $model = $model->where('published', 1); $model = $model->get(); 

Performance

 Route::get('debug/model', function () { $model = new App\Data\Entities\User; $model = $model->with('gender'); $model = $model->where('username', 'gigante'); $model = $model->get(); dd($model); }); 

I got

enter image description here

The difference is that after creating the instance you will need to do $model = $model->whatever() , because laravel returns an instance of QueryBuild, and now you have an instance of Eloquent.

So, not so much, because when Laravel cannot accomplish what you need in the model, it approaches QueryBuilder by executing newQuery (), so your codes basically work the same way.

Return to your code

 $model->published(1); 

If the Model doest does not find this method, so it will try newQuery (), so maybe.

0
source

Source: https://habr.com/ru/post/1260706/


All Articles