Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel caching queries with eager loading

the Laravel caching mechanism works fine when doing:

$users = User::remember(10)->get();

but when doing:

$users = User::with('posts','addresses')->remember(10)->get();

it doesn't cache the entire set of queries, specifically the join query (eager loading).

Is there a way to cache all the queries that are performed in the above example? Thanks!

like image 271
Jonas Avatar asked Sep 23 '14 12:09

Jonas


Video Answer


2 Answers

You can do it inline:

User::with(['posts' => function ($q) {
  $q->remember(10);
}, 'addresses' => function ($q) {
  $q->remember(10);
}])->remember(10)->get();

or in the relation definition:

public function posts()
{
  return $this->hasMany('Post')->remember(10);
}
like image 61
Jarek Tkaczyk Avatar answered Sep 28 '22 22:09

Jarek Tkaczyk


You cannot cache eagler loading queries in that way. You have 2 solutions to choose - cache::remember engine:

$users = Cache::remember('custom_cache_key', 10, function() {
    return User::with('posts', 'addresses')->get();
});

or build single query using query builder:

...->select(...)->join(...)->where(...)->remember(...)
like image 44
Wojciech Mleczek Avatar answered Sep 28 '22 22:09

Wojciech Mleczek