doufei4923
2014-01-18 11:41
浏览 120
已采纳

使用load('relation')和缓存

I know you can cache a query by appending ->remember($minutes).

However, this doesn't work when using loading on an existing Eloquent result. This is because load doesn't return a querybuilder but directly executes it.

Say you want to load the friends of a user:

$user=Auth::user();
$user->load('friends');  // How to cache these results ?

How can I cache these ?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dqzg62440 2014-01-20 02:17
    已采纳

    You can't using this code on its own. You do have two options, though:

    1) Wrap your code in a wrapper somewhere (essentially abstracting away this call), which does a cache check first, and runs these queries if the cached item does not exist or is expired.

    2) Extend the Auth library, specifically its EloquentUserProvider class, and modify the query performed by the retrieveById() method.

    You can see one method of abstracting methods and caching in Chris Fidao's Implementing Laravel. The accompanying book is handy!

    点赞 评论
  • dongyoulou4829 2014-01-19 10:35

    You have to convert User object into QueryBuilder to get access to ->remember() method Try

        User::with('friends')->where('id', Auth::user()->id)->remember()->first();
    
    点赞 评论

相关推荐 更多相似问题