Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony getting all field names from database table

I need to get all database table field names. I've already tried getting that using ClassMetadata unfortunately getColumnNames() doesn't return relational field names. and method getAssociationNames() returns names of entity properties which are not the same names and also might include fields that doesn't really exist in database when using oneToMany relations.

As people mentioned that this may be duplicate. It's not. Getting column names in a doctrine2 entity which might be a similar problem but getFieldNames method doesn't return field names which has relations to other entities.

So how do I get All column names from database table?

like image 617
Einius Avatar asked Dec 01 '22 17:12

Einius


2 Answers

I solved this with this code :

$class = $this->em->getClassMetadata('Entity');
    $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;
like image 114
Guillaume Alouege Avatar answered Dec 04 '22 09:12

Guillaume Alouege


In Doctrine the DBAL component is made to handle database-level tasks. It is also able to list all columns of a database table. The DBAL component operates on the database level wich means it does not look at any entity metadata. Assuming you have an EntityManager instance, you can get the column names like this:

// $em is your Doctrine\ORM\EntityManager instance
$schemaManager = $em->getConnection()->getSchemaManager();
// array of Doctrine\DBAL\Schema\Column
$columns = $schemaManager->listTableColumns($tableName);

$columnNames = [];
foreach($columns as $column){
    $columnNames[] = $column->getName();
}
// $columnNames contains all column names

The documentation for the schema manager can be found here: https://www.doctrine-project.org/projects/doctrine-dbal/en/2.9/reference/schema-manager.html#schema-manager

like image 24
Alex Grinspun Avatar answered Dec 04 '22 08:12

Alex Grinspun