Cakephp 3 - 在 beforefind 中获取字段和条件

Cakephp 3 - get fields and conditions in beforefind

在 cakephp 中 2.x 在 beforeFind 中,我可以检查是否设置了某些条件 !empty($queryData['conditions'][$this->alias.'.field']) 或获取可通过 $queryData['fields'] 简单检索的字段列表。如何在 cakephp 3.x 中实现这一点?

在之前找到

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

options 是空的。 $query 我可以使用 $query->where(...) 添加条件,但是如何检查哪些字段设置为要检索或已经应用了哪些条件?

谢谢

摘自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']);

因此只需调用 $query->traverse() 并提供回调闭包并在其中进行检查。另见 traverseExpressions()

谢谢指点,但是第四版的“遍历”方法我已经不行了。 我在Cake核心里看了一下:

public function beforeFind($event, $query, $options, $primary)
{
    $query
        ->clause('where')
        ->iterateParts(function ($callable) use (&$params): void {
            if ($callable->getField() === 'url') {
                // do something
            }
            $params[] = [
                $callable->getField() . ' ' . $callable->getOperator() => $callable->getValue()
            ];
        });

    $query->where($params);
}