I wondering about a subject. We can use Local scopes in Laravel but i don't know if for Symfony.
Doc : Laravel Local Scopes
Well, my question is can i use it in Symfony? Is this possible ?
Have a good day
CodePudding user response:
You can do the same with classical methods in your repository. I can show you an example(using source code from the docs):
public function findAllGreaterThanPrice(int $price, bool $includeUnavailableProducts = false): array
{
// automatically knows to select Products
// the "p" is an alias you'll use in the rest of the query
$qb = $this->createQueryBuilder('p')
->where('p.price > :price')
->setParameter('price', $price)
->orderBy('p.price', 'ASC');
if (!$includeUnavailableProducts) {
$qb->andWhere('p.available = TRUE');
}
$query = $qb->getQuery();
return $query->execute();
// to get just one result:
// $product = $query->setMaxResults(1)->getOneOrNullResult();
}
Here instead of return "$query->execute()", you can return $qb and chain methods will available. You can do something like that :
$repo->findAllActive()->findAllGreaterThan12();
Here $repo would be the repository injected in your controller.
In both method, you would have just a where and a return of querybuilder.