Search code examples
phpsymfonydoctrine-ormdoctrinesymfony4

Get table names with Symfony+Doctrine excluding tables made from relations


I'd like to get all table names from my PSQL DB using Doctrine, but I don't want relation tables, e.g.:

Tables:

  • users
  • clients
  • users_clients <-- not this

I'm currently fetching them using

$em->getConnection()->getSchemaManager()->listTables();

Any way to do it without excluding results from array using strpos()?


Solution

  • The following code should work:

    public class MyController {
        public function listTables(EntityManagerInterface $em) {
            $allMetadata = $em->getMetadataFactory()->getAllMetadata();
            $tableNames = array_map(
                function(ClassMetadata $meta) {
                    return $meta->getTableName();
                },
                $allMetadata);
    
            // do something with the table names
        }
    }
    

    Doctrine documentation: ClassMetadata#getTableName()