-->

how to make doctrine generated column name to disp

2020-06-24 08:20发布

问题:

I have an entity generated using doctrine in command line. It is as below -

/**
 * @var string
 *
 * @ORM\Column(name="COUNTRY_ID", type="string", length=2)
 */
private $cOUNTRYID;

In the database the column name is COUNTRY_ID and the SQL result will give assoc. array with COUNTRY_ID as key and its name as value.

My requirement is to have display name of SQL result to camel case. for example COUNTRY_ID should be countryId. Is there any config ready available in doctrine file to do this?.

回答1:

You have to implement a naming strategy to get camelCase autogenerated column names, as explained in Doctrine documentation.

Make a class to get camelCase name for your column names, CamelCaseNamingStrategy.php:

<?php
class CamelCaseNamingStrategy implements NamingStrategy
{
    public function classToTableName($className)
    {
        return 'cc_' . substr($className, strrpos($className, '\\') + 1);
    }
    public function propertyToColumnName($propertyName)
    {
        return $propertyName;
    }
    public function referenceColumnName()
    {
        return 'id';
    }
    public function joinColumnName($propertyName, $className = null)
    {
        return strtolower($propertyName) . ucwords($this->referenceColumnName());
    }
    public function joinTableName($sourceEntity, $targetEntity, $propertyName = null)
    {
        return strtolower($this->classToTableName($sourceEntity)) . ucwords($this->classToTableName($targetEntity));
    }
    public function joinKeyColumnName($entityName, $referencedColumnName = null)
    {
        return strtolower($this->classToTableName($entityName)) . ($referencedColumnName ?: ucwords($this->referenceColumnName()));
    }
}

Then register this new class as a service, and add it to your config.yml:

orm:
    #...
    entity_managers:
        default
            naming_strategy: my_bundle.camel_case_naming_strategy.default


回答2:

If you mean with display name the class property name, then you can do it like this:

/**
 * @var string
 *
 * @ORM\Column(name="COUNTRY_ID", type="string", length=2)
 */
private $countryId;

The name="COUNTRY_ID"in your Column definition is the column name that doctrine uses to find it in the table (table column name).

The property name $countryId is the name of the property that Doctrine uses to bind the result of the query to. So if you want the class property to be in camel case you simply need to declare the property name camel cased.