我对来自Kohana背景的Symfony非常陌生,我有一段时间习惯了Doctrine。Doctrine的createQueryBuilder绕过Entities getter方法吗?
目前我有一个产品表,我内心使用createQueryBuilder连接其他一些表,并且需要在产品实体的getter方法中添加一些额外的逻辑。但是,似乎getter方法甚至没有被使用。下面是我的一些代码片段:
//From AppBundle\Controller\ProductController
$repository = $this->getDoctrine()->getRepository('AppBundle:Product');
$products = $repository->findWithLimitNew(24);
//From AppBundle\Repositories\ProductRepository
public function findWithLimitNew($limit=1)
{
$em = $this->getEntityManager();
$qb = $em->createQueryBuilder();
$qb->select('p.name', 'p.id', 'p.slug', 'pc.name AS catname')
->from('AppBundle\Entity\Product', 'p')
->innerJoin(
'AppBundle\Entity\ProductAttributes',
'pa',
\Doctrine\ORM\Query\Expr\Join::WITH,
'p.id = pa.productId'
)
->innerJoin(
'AppBundle\Entity\ProductCategories',
'pc',
\Doctrine\ORM\Query\Expr\Join::WITH,
'pa.value = pc.id'
)
->where('pa.type = 1')
->where('pa.default = 1')
->setMaxResults($limit);
return $qb->getQuery()->getResult();
}
// From AppBundle\Entity\Product
/**
* Get name
*
* @return string
*/
public function getName()
{
#return $this->name; //<--Commenting this out for now
return 'Some stupid string';
}
// From index.twig.html
{% for product in products %}
<h1>{{product.name}}</h1>
{% endfor %}
现在你可以看到我有吸气getName()方法返回一个字符串,但在视图渲染我得到的产品名称,而不是我的字符串返回。是什么赋予了?
正如你怀疑的那样,当水合一个实体(即从数据库检索)时,Doctrine 2使用反射来直接设置实体属性。所有方法(包括构造函数)都被忽略。而DQL不是SQL。我很惊讶你的查询返回任何东西。 – Cerad
@Cerad我的查询来自一个Doctrine网站,查询工作正常。当然,我修改了我的表名。 – pogeybait
AppBundle \ Entity \ Product中的标签为pubic的是“名称”字段吗?如果是这种情况,可能是因为树枝认为该属性是公共的,并且不会打扰调用吸气剂。尽量让它变得私密并且让吸气者公开 – valepu