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?
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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With