简体   繁体   中英

Using load('relation') with caching

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 ?

您必须将User对象转换为QueryBuilder才能访问 - > remember()方法Try

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM