Skip to content
Advertisement

CakePHP 4 Modifying Query Results IN TABLE

I am looking for an example or explanation on how I can modify a query result every time a specific table is called.

All the examples I’ve seen are mainly meant for the controller. I’m kind of looking for something similar to the old function afterFind().

My goal is to put a function within my Table file to automatically modify results globally on the site.

[OR:=> If anyone knows of a way i can convert a single json column to multiple columns automatically that could fix my problem.]

PS: I have tried messing with the scheme, behaviors, and collections with no use.(unless i was using one incorrectly)

Advertisement

Answer

It really depends on how exactly you need to modify your results, “converting a single JSON column into multiple columns” is rather vague, and could be interpreted in various different ways.

Converting data in the entity is one option, but be aware that entities should be as stupid as possible, you should ideally keep them as much of a plain data transfer object as you can. Doing larger “transformative” operations in the entity itself should usually be avoided if there’s other ways of solving the problem.

A centralized approach for modifying results are result formatters for the query objects, they can easily be attached in the Model.beforeFind event/handler so that they are being applied to all queries of a specific table, or even on all tables. That’s pretty much what you would have done with afterFind in CakePHP 2.x.

Result formatters also have the advantage that they will give you the correct data when you are using queries with hydration disabled, ie queries that return arrays instead of entities.

A quick and dirty example:

public function beforeFind(CakeEventEventInterface $event, CakeORMQuery $query): CakeORMQuery
{
    return $query->formatResults(function (CakeCollectionCollectionInterface $results) {
        return $results->map(function ($row) {
            // $row is the entity (or array when hydration is disabled) in the result set            

            $row['new_field'] = 1234;

            return $row;
        });
    });
}

See also

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement