【问题标题】:Is there a way to have Entity property in Symfony, which holds combination of properties of same Entity?有没有办法在 Symfony 中拥有实体属性,它包含同一实体的属性组合?
【发布时间】:2019-05-28 07:58:11
【问题描述】:

在我的 Symfony 4 项目中,我有一个 Entity Class Users 属性 firstNamefamilyName 我想添加类似 fullName 的东西,这将是这两者的连接,但不添加列D B。例如,我需要它在前端显示和在表格中过滤。但有时也需要分开。

类定义:

/**
 * Users
 *
 * @ORM\Table(name="users")
 * @ORM\Entity
 */
class Users
{
    /**
     * @var string
     *
     * @ORM\Column(name="FIRST_NAME", type="string", length=25, nullable=false)
     */
    private $firstName;

    /**
     * @var string
     *
     * @ORM\Column(name="FAMILY_NAME", type="string", length=25, nullable=false)
     */
    private $familyName;

  // Other properties and getters + setters
}

当我使用 getter 和 setter 仅添加属性 fullName 时:

private $fullName;

public function getFullName():?string
{
    return $this->getFamilyName().', '.$this->getFirstName();
}

public function setFullName(string $fullName): self{
    return $this;
}

并在QueryBuilder 中使用它

createQueryBuilder()->select('u.fullName')->from('App\Entity\Users','u')->where('u.id = ?')...

然后我得到了这个错误:

'fullName FROM': Error: Class App\Entity\Users has no field or association named fullName

有没有一种简单的方法,如何对 Doctrine 说这个属性不是来自 DB,而是作为“虚拟列”存在?我知道,我可以使用 DQL 函数 Concat 等,但我需要这个。从我的角度来看,这更好一点。

【问题讨论】:

  • 在查询中连接是不可能的吗?如 ->select('CONCAT(user.firstname, \' \', user.lastname) AS full_name')
  • 为什么在 Doctrine 中需要它?仅使用 getter 方法 - 无需附加属性 - 您可以在 php / twig 中任何需要的地方使用它。要在 Doctrine 中过滤,您需要 2 个单独的 andWhere() 子句。
  • @DylanKas 是的,这是不可能的。
  • @jeroen 我知道,但我不能在 queryBuilder 中使用它,这就是我需要的。

标签: php entity-framework doctrine-orm doctrine symfony4


【解决方案1】:
public function getFullName(): string
{
    return \implode(', ', \array_filter([$this->getFamilyName(), $this->getFirstName()]));
}

这就是您从 Entity 中检索 fullName 所需的全部内容。

但由于您在映射或表中没有真正的列,您应该使用这样的 DQL 表达式:

createQueryBuilder()->select("CONCAT(u.familyName, ', ', u.firstName)")->from('App\Entity\Users','u')->where('u.id = ?')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-28
    • 1970-01-01
    • 2013-09-06
    相关资源
    最近更新 更多