CakePHP3 After removing afterFind, where can I check if the query result was empty?

Before I checked the afterFind callback if the search result is empty. Since the callback has been removed in recent versions, where would there be a place to test this due to the behavior?

I'm not sure if this is what I need. My use case: I want to know if there is no query result. Then I would create a default entry, so it has 1 result.

+3


source to share


1 answer


https://book.cakephp.org/3.0/en/appendices/orm-migration.html#no-afterfind-event-or-virtual-fields

Once defined, you can access the new property with $ user-> full_name. Using Result Modification with Map / Shrink ORM function allows you to create aggregated data from your results, which is another use case for which the afterFind callback was often used.

Call count () on ResultSet object

https://api.cakephp.org/3.4/class-Cake.ORM.ResultSet.html#_count

Not sure why you don't use this and want to do the invoice manually, but continue.

Using resultFormatter ()

https://book.cakephp.org/3.0/en/orm/query-builder.html#adding-calculated-fields

You will have to add a formatter to your beforeFind () file for the request. You can add a custom find that will add it as well. Sample code (taken from the docs):



$query->formatResults(function (\Cake\Collection\CollectionInterface $results) {
    return $results->map(function ($row) {
        $row['age'] = $row['birth_date']->diff(new \DateTime)->y;
        return $row;
    });
});

      

Count the results.

Using map / reduce

https://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#map-reduce

Most often, search operations require post-processing of the data that is in the database. While getter methods can handle most of generating virtual properties or formatting special data, sometimes you need to change the data structure in a more fundamental way.

The behavior will need to add a mapper / reducer to your beforeFind () to the request. You can add a custom find that will add it as well. Sample code (taken from the docs):

$articlesByStatus = $articles->find()
    ->where(['author_id' => 1])
    ->mapReduce($mapper, $reducer);

      

Check the above link for a detailed explanation including examples of creating a matcher and reducer.

+1


source







All Articles