简体   繁体   English

ZF2 Doctrine - 使用查询构建器如何指向存储库中的自定义方法

[英]ZF2 Doctrine - using query builder how to point at custom methods in repository

I am struggling with this one and hope someone is able to help. 我正在努力解决这个问题,并希望有人能够提供帮助。 Building a webapp using ZF2 and Doctrine I am trying to build a query using Doctrine's query builder making use of a custom method in my entity file. 使用ZF2和Doctrine构建webapp我正在尝试使用Doctrine的查询构建器在我的实体文件中使用自定义方法来构建查询。 For simple example entity file as follows (shortened for clarity): 对于简单示例实体文件如下(为清楚起见缩短):

/**
 * Get firstName
 *
 * @return string 
 */
public function getFirstName()
{
    return $this->firstName;
}

/**
 * Get lastName
 *
 * @return string 
 */
public function getLastName()
{
    return $this->lastName;
}
public function getFullName()
{
    return $this->getFirstName() . ' ' . $this->getLastName();
}

So the first and last name are directly mapped to dB columns, getFullName is a custom method in the entity file. 因此,名字和姓氏直接映射到dB列,getFullName是实体文件中的自定义方法。 Then extending the entity with a custom repository for queries I would like to make use of the getFullName method. 然后使用自定义存储库扩展实体以进行查询,我想使用getFullName方法。 I have the following in the repository (which extends the entity file): 我在存储库中有以下内容(扩展了实体文件):

$qb = $this->_em->createQueryBuilder();
$qb->select('employee')
    ->from('Application\Entity\Employee', 'employee')
    ->andWhere('employee.fullName = :foo')
    ->setParameter('foo', 'Joe Bloggs');

$query = $qb->getQuery();

I was hoping in the andWhere statement it would translate the employee.fullName to find the getFullName method but it appears not. 我希望在andWhere语句中它会转换employee.fullName来查找getFullName方法,但它看起来不是。 Does anyone have any ideas please? 有没有人有任何想法吗?

Thank you James 谢谢詹姆斯

The simple answer is: "You can not!". 简单的答案是:“你做不到!”。 The getFullName method has nothing to do with doctrine, because it exists only in the model. getFullName方法与doctrine无关,因为它仅存在于模型中。

The easiest way to simulate what you want is to split the name into the parts and use it: 模拟所需内容的最简单方法是将名称拆分为部分并使用它:

$fullName = 'Joe Bloggs';
list($firstName, $lastName) = explode(' ', $fullName);
$qb = $this->_em->createQueryBuilder();
$qb->select('employee')
    ->from('Application\Entity\Employee', 'employee')
    ->andWhere('employee.firstName = :first')
    ->andWhere('employee.lastName = :last')
    ->setParameter('first', $firstName)
    ->setParameter('last', $lastName);

$query = $qb->getQuery();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM