cakephpcakephp-3.x

Cakephp 3 - get fields and conditions in beforefind


In cakephp 2.x in beforeFind I could check if some condition is set by !empty($queryData['conditions'][$this->alias.'.field']) or get the list of fields that would be retrived simply by $queryData['fields']. How to achieve this in cakephp 3.x ?

In beforeFind

public function beforeFind(Event $event, Query $query, $options, $primary)
{
}

the options is empty. The $query I can use to add conditions by $query->where(...), but how to check what fields are set to be retrieved or what conditions are already applied ?

Thanks


Solution

  • Taken from the CakePHP 3.0 API documentation:

    traverse( callable $visitor , array $parts [] )
    

    Will iterate over every specified part. Traversing functions can aggregate results using variables in the closure or instance variables. This function is commonly used as a way for traversing all query parts that are going to be used for constructing a query.

    The callback will receive 2 parameters, the first one is the value of the query part that is being iterated and the second the name of such part.

    Example:

    $query->select(['title'])->from('articles')->traverse(function ($value, $clause) {
        if ($clause === 'select') {
            var_dump($value);
        }
    }, ['select', 'from']);
    

    So just call $query->traverse() and provide the callback closure and do your checks inside of it. See also traverseExpressions().