Метод where класса Criteria
Метод where класса Criteria задаёт
первое условие фильтрации элементов коллекции.
Критерий передаётся в методы matching
или filter коллекции. Первым параметром
передаётся условие сравнения, вторым - значение,
с которым сравнивается поле элемента.
Синтаксис
public function where(string $expr, mixed $value): Criteria
Метод возвращает сам объект Criteria,
поэтому вызовы можно объединять в цепочку
с методами andWhere, orWhere,
orderBy, setFirstResult
и setMaxResults.
Пример
Давайте отфильтруем коллекцию по полю
active:
<?php
namespace AppService;
use DoctrineCommonCollectionsArrayCollection;
use DoctrineCommonCollectionsCriteria;
class ArticleService
{
public function filter(): ArrayCollection
{
$arr = [
['title' => 'abcde', 'active' => true],
['title' => 'article', 'active' => false],
['title' => 'user', 'active' => true],
];
$coll = new ArrayCollection($arr);
$criteria = Criteria::create()
->where(Criteria::expr()->eq('active', true));
return $coll->matching($criteria);
}
}
?>
Результат выполнения кода:
["abcde", "user"]
Пример
Давайте отфильтруем коллекцию по числовому
полю price с помощью оператора
gt:
<?php
namespace AppService;
use DoctrineCommonCollectionsArrayCollection;
use DoctrineCommonCollectionsCriteria;
class ArticleService
{
public function filter(): ArrayCollection
{
$arr = [
['title' => 'abcde', 'price' => 100],
['title' => 'article', 'price' => 200],
['title' => 'user', 'price' => 300],
];
$coll = new ArrayCollection($arr);
$criteria = Criteria::create()
->where(Criteria::expr()->gt('price', 150));
return $coll->matching($criteria);
}
}
?>
Результат выполнения кода:
["article", "user"]
Пример
Давайте объединим метод where
с методом andWhere и добавим
сортировку через orderBy:
<?php
namespace AppService;
use DoctrineCommonCollectionsArrayCollection;
use DoctrineCommonCollectionsCriteria;
class ArticleService
{
public function filter(): ArrayCollection
{
$arr = [
['title' => 'abcde', 'price' => 100, 'active' => true],
['title' => 'article', 'price' => 200, 'active' => false],
['title' => 'user', 'price' => 300, 'active' => true],
];
$coll = new ArrayCollection($arr);
$criteria = Criteria::create()
->where(Criteria::expr()->eq('active', true))
->andWhere(Criteria::expr()->gt('price', 150))
->orderBy(['price' => 'DESC']);
return $coll->matching($criteria);
}
}
?>
Результат выполнения кода:
["user"]