Reputation: 226
How do I cache the lazy eager loading queries based on the model relationships. For example -
$books = App\Book::all();
$books->load('author', 'publisher');
I can cache the first query with something like this
$books = Cache::remember('allbooks', 60, function() {
return App\Book::all();
});
How do I cache the second query?
If there is no direct way, please suggest any workaround, possibly with a sample code.
Update: I need the second query to be executed separately so I can clear these two cache keys separately.
Upvotes: 2
Views: 894
Reputation: 919
You can use the query builder with
method:
$books = App\Book::with(['author','publisher'])->get();
Or simply do the additional load inside the cache callable:
$books = Cache::remember('allbooks', 60, function() {
return App\Book::all()->load('author', 'publisher');
});
Update: to keep the caches separated you need two variables, like this:
$books = Cache::remember('allbooks', 60, function()
{
return App\Book::all();
});
$booksAP = Cache::remember('allbooks_ap', 60, function() use ($books)
{
return $books->load('author', 'publisher');
});
Upvotes: 3