Eloquent的Model :: query()是什么意思?

Sha*_*med 4 laravel eloquent laravel-query-builder laravel-5.6

任何人都可以详细解释一下Eloquent的Model::query()意思吗?

Dev*_*von 11

每当您在Eloquent中查询模型时,您都在使用Eloquent Query Builder.Eloquent模型使用魔术方法(__ call,__ callStatic)将调用传递给查询构建器. Model::query()返回此查询构建器的实例.

因此,由于将where和其他查询调用传递给查询构建器:

Model::where()->get();
Run Code Online (Sandbox Code Playgroud)

是相同的:

Model::query()->where()->get();
Run Code Online (Sandbox Code Playgroud)

我在过去发现自己使用Model :: query()的地方是我需要实例化一个查询然后根据请求变量建立条件.

$query = Model::query();
if ($request->color) {
    $query->where('color', $request->color);
}
Run Code Online (Sandbox Code Playgroud)

希望这个例子有帮助.

  • 谢谢@德文郡。您能提供文档参考吗? (2认同)