Thursday, January 13, 2022

[FIXED] Cakephp 3 - cache query with limit

Issue

I have a list of topics, 15 by default, and a load more button which load 15 more topics with an ajax request. It takes too much time for initial query to get first 15 topics so I cached the query, which looks like this:

$query = "SELECT *, views + views_rom + views_eng + views_rus as views
    FROM topics Topic
    LEFT JOIN topics_practices  TopicsPractice on (TopicsPractice.topic_id = Topic.id  )
    LEFT JOIN practices  Practice on (TopicsPractice.practice_id = Practice.id)
    LEFT JOIN topic_comments  TopicComment on (TopicComment.topic_id = Topic.id )
    LEFT JOIN slugs  Slug on (Slug.table = 'topics' AND Slug.item_id = Topic.id)
    WHERE Topic.id IN 
        (SELECT id FROM (
            SELECT  t.id
            FROM topics t 
            LEFT JOIN topic_comments tc on (tc.topic_id = t.id ) 
            LEFT JOIN topics_practices tp on (tp.topic_id = t.id ) 
            LEFT JOIN topics_tags  TopicsTag on (TopicsTag.topic_id = t.id)  
            WHERE $conditions
            GROUP BY t.id 
            ORDER BY $orderSubsidiary
            LIMIT $limit
        ) temp) 
    ORDER BY $order    
   ";

$topics = Cache::remember(str_replace(' ','_',$conditions).'_setTopics_cache', function() use ($query) { $topics = $this->query($query); }, '5min');

The problem I have is that every time I make the ajax request I get back the first 15 topics. My query limit does not change. Is there a way to change the limit value in my cached query?


Solution

Change your cache key to include your limit in some form so that you have a unique key for each query. When your query changes, the key needs to change as well so that you can fetch and cache those results instead of using the previous cached set for the previous query.



Answered By - Symeon Quimby

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.