Метод orWhere класса Criteria
Метод orWhere класса Criteria добавляет
новое условие к фильтру коллекции, объединяя его
с предыдущими условиями через логическое ИЛИ.
Первым параметром передаётся строка сравнения,
вторым - значение, с которым сравнивается элемент.
Метод удобен, когда нужно выбрать элементы, удовлетворяющие хотя бы одному из нескольких условий.
Синтаксис
public function orWhere(string $expr, mixed $value): Criteria
Пример
Давайте создадим критерий, который выберет элементы
с id равным 1 или с id равным 3:
<?php
namespace AppService;
use DoctrineCommonCollectionsArrayCollection;
use DoctrineCommonCollectionsCriteria;
class ArticleService
{
public function filter(): array
{
$collection = new ArrayCollection([
['id' => 1, 'title' => 'article 1'],
['id' => 2, 'title' => 'article 2'],
['id' => 3, 'title' => 'article 3'],
['id' => 4, 'title' => 'article 4'],
['id' => 5, 'title' => 'article 5'],
]);
$criteria = Criteria::create()
->where(Criteria::expr()->eq('id', 1))
->orWhere(Criteria::expr()->eq('id', 3));
$res = $collection->matching($criteria)->toArray();
return $res;
}
}
?>
Результат выполнения кода:
[
['id' => 1, 'title' => 'article 1'],
['id' => 3, 'title' => 'article 3'],
]
Пример
Давайте объединим несколько условий через orWhere
и отфильтруем коллекцию по полю title:
<?php
namespace AppService;
use DoctrineCommonCollectionsArrayCollection;
use DoctrineCommonCollectionsCriteria;
class ArticleService
{
public function filter(): array
{
$collection = new ArrayCollection([
['id' => 1, 'title' => 'article'],
['id' => 2, 'title' => 'hello'],
['id' => 3, 'title' => 'user'],
['id' => 4, 'title' => 'abcde'],
]);
$criteria = Criteria::create()
->where(Criteria::expr()->eq('title', 'article'))
->orWhere(Criteria::expr()->eq('title', 'user'))
->orWhere(Criteria::expr()->eq('title', 'abcde'));
$res = $collection->matching($criteria)->toArray();
return $res;
}
}
?>
Результат выполнения кода:
[
['id' => 1, 'title' => 'article'],
['id' => 3, 'title' => 'user'],
['id' => 4, 'title' => 'abcde'],
]