Laravel 中的 newQuery()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40932411/
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
newQuery() in Laravel
提问by panthro
Whats the difference between doing:
这样做有什么区别:
$model = User::newQuery();
$model->published(1);
$model->get();
And:
和:
$model = User;
$model = $model->published(1);
$model = $model->get();
I know with the second example you have to assign the call back to the model. But is there any difference to these?
我知道在第二个示例中,您必须将回调分配给模型。但是这些有什么区别吗?
Note, I'm not chaining as there would be some conditions between checking if it should be published or not etc.
请注意,我没有链接,因为在检查它是否应该发布等之间会有一些条件。
回答by Antonio Carlos Ribeiro
It depends on what published() is. Changing your code a bit:
这取决于publish() 是什么。稍微改变你的代码:
$model = User::newQuery();
$model->where('published', 1);
$model->get();
or
或者
$model = new User;
$model = $model->where('published', 1);
$model = $model->get();
Doing
正在做
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
我有
The difference is that once instantiated, you'll have to do $model = $model->whatever()
, because laravel is returning an instance of QueryBuild and you now have an instance of Eloquent.
不同之处在于,一旦实例化,您就必须这样做$model = $model->whatever()
,因为 laravel 正在返回一个 QueryBuild 实例,而您现在拥有了一个 Eloquent 实例。
So, not much different, because when Laravel is not able to execute what you need in the model, it goes right to the QueryBuilder, by executing newQuery(), so your codes are doing basically the same.
所以,没什么不同,因为当 Laravel 无法在模型中执行你需要的东西时,它会直接进入 QueryBuilder,通过执行 newQuery(),所以你的代码基本上是一样的。
Backing to your code,
回到你的代码,
$model->published(1);
If Model doest not find that method, so it will try newQuery(), so, maybe.
如果 Model 没有找到那个方法,那么它会尝试 newQuery(),所以,也许吧。