Reputation: 1382
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?
Upvotes: 6
Views: 13618
Reputation: 41
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
Upvotes: 4
Reputation: 790
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;
Upvotes: 15
Reputation: 1382
I solved this problem by using raw sql query. In my case as I was needing all the data from the table for the data export I used the query "SELECT * FROM $tableName"
and then I used array_keys
function with the first result row. In case I need to get entity field names representing that column you can use:
$entityManager->getClassMetadata->getFieldForColumn($column);
It doesn't take arguments as array so I have to foreach all db column names with this function but with this
Upvotes: 0