Search code examples
cakephp-3.0cakephp-3.1cakephp-3.x

How to delete data in custom finder method in CakePHP 3


I want to delete data in custom finder method.

Custom finder method document

My code:

public function findPREACTIVE(Query $query, array $options) {
    $query->delete()
            ->where(['member_status' => -1])
            ->andWhere(['registered >= DATE_SUB(NOW(), INTERVAL 72 HOUR)'])->execute();

    return $query
                    ->where(['email' => $options['email'], 'token_key' => $options['token_key']])
                    ->andWhere(['member_status' => -1])
                    ->andWhere(['registered < DATE_SUB(NOW(), INTERVAL 72 HOUR)']);
}

When i call this finder, i get error:

You cannot call all() on a non-select query. Use execute() instead.

Is there have solution for this case?


Solution

  • You'll have to issue a separate query. What you are doing there will mess up the finder query, which is ment to be a select query.

    $this
        ->query()
        ->delete()
        ->where(['member_status' => -1])
        ->andWhere(['registered >= DATE_SUB(NOW(), INTERVAL 72 HOUR)'])->execute();
    

    Use applyOptions() in case you need the finder options to be applied to the delete query too.

    $this
        ->query()
        ->delete()
        ->applyOptions($options)
        // ...