phpdoctrine-ormsymfony4classname

Symfony get className object from String class declaration


I have this code that returns column names of the className declared in the 2nd line :

 public function listColumns(EntityManagerInterface $em  ) {
    $class = $em->getClassMetadata(Assure::class);
    $fields = [];
    if (!empty($class->discriminatorColumn)) {
        $fields[] = $class->discriminatorColumn['name'];
    }
    $fields = array_merge($class->getColumnNames(), $fields);
    foreach ($fields as $index => $field) {
        if ($class->isInheritedField($field)) {
            unset($fields[$index]);
        }
    }
    foreach ($class->getAssociationMappings() as $name => $relation) {
        if (!$class->isInheritedAssociation($name)){
            foreach ($relation['joinColumns'] as $joinColumn) {
                $fields[] = $joinColumn['name'];
            }
        }
    }
    return $fields;
}

I am trying to make this function parametrable so I can give it every time which table/className I am trying to get its columns


Solution

  • This is a possible solution to do what I want (extracting table column names ) differently :

       public function listColumns2(EntityManagerInterface $em  ) {
    
        $conn = $this->getEntityManager()->getConnection();
    
        $sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 
               N'Assure' ";
        $stmt = $conn->prepare($sql);
        $stmt->execute();
    
        return $stmt->fetchAllAssociative();
       }