Search code examples
phpsymfonysearchfilterdql

How to create a symfony 2 search filter base on the multiple tables entities


I want to build a search filter in symfony. I am using symfony 2.8. I have four table with respected entities. Table are

professional
professional_pets
professional_categories
professional_organization

professional_pets table contain professionalId and petId for store the relation pet and professional. same way the professional_categories table contains professionalId and categoryId fields to store relation between professional and Categories. Same case with professional_organization.

What I want that I want a dql query to filter professionals form professionals table if it is possible which can extract only those records from professional table which have relation with specific in professional_pet, professional_categories and professional_organizations.
In other work I want tho create filter for professinals in professionals table base on the if there is a relation sotre for them in professional_pet, professional_categories and professional_organizations tables.

I am attaching a snapshot of filter. Thanks for help in advance. enter image description here


Solution

  • Edit:

    <?php
    
    namespace CommonBundle\Entity\Children;
    
    use Doctrine\ORM\EntityRepository;
    use Doctrine\ORM\QueryBuilder;
    
    
    class professionalRepository extends EntityRepository
    {
    
        public function findAllBySearch($searchValues)
        {
            /** @var QueryBuilder $query */
            //professional entity
            $query = $this->createQueryBuilder('p');
    
            if(!empty($searchValues['pet_id'])){
                $query->join('AppBundle:ProfessionalPets', 'pp', 'WITH', 'pp.professionalId = p.id');
                $query->andWhere('pp.petId = :pet_id')
                    ->setParameter('pet_id', $searchValues['pet_id']);
            }
            if(!empty($searchValues['cat_id'])){
                $query->join('AppBundle:ProfessionalCategories', 'pc', 'WITH', 'pc.professionalId = p.id');
                $query->andWhere('pc.categoryId = :cat_id')
                    ->setParameter('cat_id', $searchValues['cat_id']);
            }
            if(!empty($searchValues['org_id'])){
                $query->join('AppBundle:ProfessionalOrganization', 'po', 'WITH', 'po.professionalId = p.id');
                $query->andWhere('po.organizationId = :org_id')
                    ->setParameter('org_id', $searchValues['org_id']);
            }
    
            return $query->getQuery()->getResult();
        }
    }
    

    Since I don't know what your bundles and entity classes names are, you will need to modify them.