Answer the question
In order to leave comments, you need to log in
How to use filters in Symfony2?
Good afternoon. From Yii experience, I remember there were scopes. What are the analogs in Symfony?
I make product selections according to a table with different conditions using sorting and all kinds of conditions on the selection. But the only thing that should always be is to choose the item count > 0 . Only in the admin panel I need to choose without this condition.
Examples are welcome!
What did I do.
<?php
namespace Bundle\Repository;
use Doctrine\ORM\EntityRepository;
class ItemRepository extends EntityRepository
{
public function exist()
{
return
$this->createQueryBuilder('i')
->where('i.count > :count')
->setParameter(':count', 0);
}
}
<?php
namespace Bundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class DefaultController extends Controller
{
public function indexAction()
{
$em = $this->getDoctrine()->getManager('');
$top = $em->getRepository('Bundle:Item')->exist()
->where('i.price > :price')
->andWhere('i.rating > :rate')
->setParameters(array(':price' => 10000, ':rate' => 3))
->getQuery()
->getResult();
return $this->render('Bundle:Default:index.html.twig', array(
'top' => $top
));
}
}
Answer the question
In order to leave comments, you need to log in
Make a QueryBuilder, and immediately put the necessary condition in it. And add additional conditions to the builder on each page.
Alternatively, create a parent class for all controllers, and put a method there that creates this QueryBuilder and returns a link to it.
But it would be much better to create a service that encapsulates all work with the entity, and make the service have several methods that return a ready-made entity, possibly from the cache.
And in the doctrine you have all the selections should be in your repository, and there you already decide what, how and when to apply and how to use the query builder. That is, if you want to take some data, you must take the repository and ask him to give you data. That is, only repositories will depend on the doctrine.
Repositories can be registered as regular services:
class: Doctrine\ORM\EntityRepository
factory_service: doctrine.orm.default_entity_manager
factory_method: getRepository
arguments:
- Acme\CustomerBundle\Entity\Customer
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question