0

For example: - Query 1 - Select name from admin, and Query 2 - Select name from user

Both are identical tables with different names, so I am doing like this but it's not working:

$entityName = User::class;
$query = $this->_em->createQueryBuilder()
         ->select('a.name')
         ->from($entityName, 'a')
         ->where('a.deleted = 0');
if($loggedinuser == 'Admin'){
   $entityName = Admin::class;
   $query->andWhere('a.active = 1');
}else{
   $entityName = User::class;
}
Ak Dutta
  • 3
  • 3
  • While they should be in different repositories for the two entities - are you setting `$entityName` after it's used in the `->from()` (as this code does)? – Alister Bulman Jul 14 '21 at 21:32
  • I used $entityName as the default first after that I applying conditions @AlisterBulman – Ak Dutta Jul 14 '21 at 21:38

1 Answers1

0

I'm still not sure what you're doing there (or why it's 'not working' - what is it that doesn't work?), as you are apparently checking and changing $entityName after the fact.

From your use of $this->_em, this may be within a repository class method, where you could either put a simple, specialised method to make the most appropriate query.

// in the class: AdminRepository
public function getActiveAdminUsers()
{
    return $this->findBy([
        'deleted' => 0,
        'active' => 1,
    ]);  // includes all fields, not just name

    // OR
    // in the AdminRepository, we would be querying the Admin table
    $query = $this->getEntityManager()->createQueryBuilder('a');
    $query->select(['a.name'])
        ->where('a.deleted = 0')
        ->andWhere('a.active = 1')
    ;

    return $query->getQuery()->getArrayResult();
}
Alister Bulman
  • 34,482
  • 9
  • 71
  • 110