Skip to content

Commit 9f4d333

Browse files
authored
Improve performance on queries with skipAddTrashCondition. (#71)
Move query scanning to a function to allow users to override/skip it based on their requirements.
1 parent 6101d78 commit 9f4d333

File tree

1 file changed

+23
-6
lines changed

1 file changed

+23
-6
lines changed

src/Model/Behavior/TrashBehavior.php

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,26 @@ public function trash(EntityInterface $entity, array $options = []): bool
180180
*/
181181
public function beforeFind(EventInterface $event, SelectQuery $query, ArrayObject $options, bool $primary): void
182182
{
183+
if (!empty($options['skipAddTrashCondition'])) {
184+
return;
185+
}
186+
183187
$field = $this->getTrashField();
188+
189+
if ($this->shouldAddTrashCondition($query, $field)) {
190+
$query->andWhere([$field . ' IS' => null]);
191+
}
192+
}
193+
194+
/**
195+
* Whether we need to add the trash condition to the query
196+
*
197+
* @param \Cake\ORM\Query\SelectQuery $query Query.
198+
* @param string $field Trash field
199+
* @return bool
200+
*/
201+
protected function shouldAddTrashCondition(SelectQuery $query, string $field): bool
202+
{
184203
$addCondition = true;
185204

186205
$query->traverseExpressions(function ($expression) use (&$addCondition, $field): void {
@@ -205,11 +224,7 @@ public function beforeFind(EventInterface $event, SelectQuery $query, ArrayObjec
205224
}
206225
});
207226

208-
$option = $query->getOptions();
209-
210-
if ($addCondition && empty($option['skipAddTrashCondition'])) {
211-
$query->andWhere($query->newExpr()->isNull($field));
212-
}
227+
return $addCondition;
213228
}
214229

215230
/**
@@ -221,7 +236,9 @@ public function beforeFind(EventInterface $event, SelectQuery $query, ArrayObjec
221236
*/
222237
public function findOnlyTrashed(SelectQuery $query, array $options): SelectQuery
223238
{
224-
return $query->andWhere($query->newExpr()->isNotNull($this->getTrashField()));
239+
return $query
240+
->applyOptions(['skipAddTrashCondition' => true])
241+
->andWhere($query->newExpr()->isNotNull($this->getTrashField()));
225242
}
226243

227244
/**

0 commit comments

Comments
 (0)