【问题标题】:how to make doctrine generated column name to display in camel case in doctrine 2 symfony?如何使学说生成的列名在学说2 symfony中以驼峰式显示?
【发布时间】:2016-12-01 07:10:06
【问题描述】:

我有一个在命令行中使用教义生成的实体。如下-

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

在数据库中,列名是COUNTRY_ID,SQL 结果将给出 assoc。以COUNTRY_ID 为键,名称为值的数组。

我的要求是将 SQL 结果的显示名称显示为驼峰式。例如COUNTRY_ID 应该是countryId。学说文件中是否有任何可用的配置来执行此操作?

【问题讨论】:

  • 你可以c/p你的查询吗?
  • SQL 结果的显示名称到底是什么意思?
  • 好的。我将更详细地解释。我的实体 'TFixed.php' 的内容如下。 namespace RestBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * TFixedFees * * @ORM\Table() * @ORM\Entity(repositoryClass="RestBundle\Entity\TFixedRepository") */ class TFixed { /** * @var integer * * @ORM\Column(name="USER_ID", type="integer") */ private $uSERID; 当我做任何 SQL 查询时,它的结果数组将有 {'USER_ID':'67637673'}。但我需要结果是骆驼案。

标签: symfony doctrine-orm entities


【解决方案1】:

您必须实施命名策略才能获取 camelCase 自动生成的列名,如 explained in Doctrine documentation

创建一个类来获取列名的驼峰命名,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()));
    }
}

然后将这个新类注册为服务,并将其添加到您的 config.yml

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

【讨论】:

  • 我认为 OP 从现有数据库中生成他的实体(属性名称)。有没有可能用命名策略设置像columnNameToProperty 这样的东西?
  • @Wilt 不确定,我仍然认为这是关于在 final 中获取 camelCase 列名。对于您的问题,我认为这可以解决问题:symfony.com/doc/current/doctrine/reverse_engineering.html(没有决定命名策略的想法。)
【解决方案2】:

如果您的意思是显示名称是类属性名称,那么您可以这样做:

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

您的 Column 定义中的 name="COUNTRY_ID" 是教义用来在表中查找它的列名(表列名)。

属性名称$countryId 是Doctrine 用来绑定查询结果的属性名称。因此,如果您希望类属性为驼峰式,您只需声明属性名称为驼峰式。

【讨论】:

  • 谢谢。但是属性名称都是自动生成的,知道如何将它设置为以驼峰形式生成吗?
  • @ManojKumar 如果您将表名 COUNTRY_ID 更改为 country_id,它将变成您想要的驼峰式。这是可能的还是您不能更改表名?
  • 否则你可以在the Doctrine documentation on Implementing a NamingStrategy阅读,如果你能找到解决方案...
猜你喜欢
  • 1970-01-01
  • 2012-06-11
  • 1970-01-01
  • 1970-01-01
  • 2016-01-01
  • 1970-01-01
  • 2011-05-26
  • 2015-02-28
  • 1970-01-01
相关资源
最近更新 更多