【发布时间】:2019-05-28 07:58:11
【问题描述】:
在我的 Symfony 4 项目中,我有一个 Entity Class Users 属性 firstName 和 familyName 我想添加类似 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