Laravel 是否每次调用 Auth::user() 时都查询数据库?
Does Laravel query database each time I call Auth::user()?
在我的 Laravel 应用程序中,我在多个地方使用了 Auth::user()
。我只是担心 Laravel 可能会在每次调用 Auth::user()
时进行一些查询
请指教
没有缓存用户模型。我们来看看Illuminate\Auth\Guard@user
:
public function user()
{
if ($this->loggedOut) return;
// If we have already retrieved the user for the current request we can just
// return it back immediately. We do not want to pull the user data every
// request into the method because that would tremendously slow an app.
if ( ! is_null($this->user))
{
return $this->user;
}
正如评论所说,第一次检索用户后,它将存储在 $this->user
中,并在第二次调用时返回。
对于同一个请求,如果你 运行 Auth::user()
多次,它只会 运行 1 query
而不是多次。
但是,如果您使用 Auth::user()
调用另一个请求,它将再次 运行 1 query
。
出于安全的考虑,在发出第一个请求后不能为所有请求缓存。
因此,它 运行 每个请求 1 个查询,无论您调用的次数如何。
我看到这里使用了一些会话来避免 运行 多重查询,所以你可以试试这些代码:http://laravel.usercv.com/post/16/using-session-against-authuser-in-laravel-4-and-5-cache-authuser
谢谢
在我的 Laravel 应用程序中,我在多个地方使用了 Auth::user()
。我只是担心 Laravel 可能会在每次调用 Auth::user()
请指教
没有缓存用户模型。我们来看看Illuminate\Auth\Guard@user
:
public function user()
{
if ($this->loggedOut) return;
// If we have already retrieved the user for the current request we can just
// return it back immediately. We do not want to pull the user data every
// request into the method because that would tremendously slow an app.
if ( ! is_null($this->user))
{
return $this->user;
}
正如评论所说,第一次检索用户后,它将存储在 $this->user
中,并在第二次调用时返回。
对于同一个请求,如果你 运行 Auth::user()
多次,它只会 运行 1 query
而不是多次。
但是,如果您使用 Auth::user()
调用另一个请求,它将再次 运行 1 query
。
出于安全的考虑,在发出第一个请求后不能为所有请求缓存。
因此,它 运行 每个请求 1 个查询,无论您调用的次数如何。
我看到这里使用了一些会话来避免 运行 多重查询,所以你可以试试这些代码:http://laravel.usercv.com/post/16/using-session-against-authuser-in-laravel-4-and-5-cache-authuser
谢谢