代码之家  ›  专栏  ›  技术社区  ›  Pankaj

从缓存中获取关系对象

  •  0
  • Pankaj  · 技术社区  · 8 年前

    $query = (new UserModel())->newQuery();
    $query->with("Role");
    $data = $query->get(["UserName", "EmailAddress", "User_ID"]);
    

    我在数据库中有3个角色,它们在缓存中。 有没有办法更改这行代码: $query->with("Role"); 这样,在每次获取用户时,它将不需要从数据库中获取角色。

    1 回复  |  直到 8 年前
        1
  •  0
  •   Fjarlaegur    8 年前

    也许你可以从Eloquent那里了解到检索到的事件。从数据库检索模型时,可以从缓存中获取角色并在模型上设置它。也许这对你来说是个解决办法?

    https://laravel.com/docs/5.6/eloquent#events

    /**
     * Boot the model.
     */
    protected static function boot()
    {
        parent::boot();
        static::retrieving(function ($user) {
            $user->fetchFromCache("Role"); //replace this line with however you could fetch it from the cache
        });
    }