Search code examples
phplithium

How to remove rows or filter a recordset or collection


I would like to know if there is a way to remove rows or filter a recordset or collection.

For example, if I have two tables: one for questions and one for the answer choices. The questions belong to different forms. Questions 1-10 belongs to form a, 11-20 belong to form b. Depending on the answers of the previous questions, certain questions may or may not show up, and certain answers later on may or may not show up. Instead of constantly hitting the database, I want to cache the recordset or collection of questions belonging to each form into memory and filter off of the in memory set of questions per session.

This way each user will only hit the database once, at the beginning of their session, instead of every time they click on next.


Solution

  • The Collection object used by the models is extended from lithium\util\Collection which provides a method for filtering an existing collection and returning a new one based on a user provided closure.

    $newQuestions = $oldQuestions->find(function($question) {
        if (your new criteria) { 
            return true;
        }
        return false;
    });
    

    Simply determine the criteria you wish to apply and perform the filtering in the closure. Once it runs you should have a new Collection object with only the records that matched.