我按照Doctrine模型类中设置自定义findOneByJoinedToCategory($ id)函数的示例进行了操作,如以下文档中所述:
http://symfony.com/doc/current/book/doctrine.html
就我而言,我有一个名为TestVendorCategory的模型类,其中包含一堆属性和此函数:
public function findOneByNameJoinedToVendorCategoryMappings($vendorCategoryName)
{
$query = $this->getEntityManager()
->createQuery('
SELECT vc, vcm FROM TestCoreBundle:VendorCategory vc
JOIN vcm.vendorCategoryMapping vcm
WHERE vc.name = :name'
)->setParameter('name', $vendorCategoryName);
try
{
return $query->getSingleResult();
}
catch (\Doctrine\ORM\NoResultException $e)
{
return null;
}
}
在我的控制器中,我称之为:
$vendorCategoryMapping = $this->em->getRepository("TestCoreBundle:VendorCategory")->findOneByNameJoinedToVendorCategoryMappings($vendorCategoryName);
当我进入浏览器并使用此调用执行此操作时,收到以下错误消息:
实体'Test \ CoreBundle \ Entity \ VendorCategory'没有字段'nameJoinedToVendorCategoryMappings'。因此,您不能在实体的存储库中调用“findOneByNameJoinedToVendorCategoryMappings”
看起来Symfony 2.1希望findOneBy ...()方法只反映现有字段的名称,而不是自定义“JoinedTo ...”种类的方法。我错过了什么吗?文档显示了一个这样的例子,据说它可以工作。我正在使用注释,但这种方法没有。谢谢!
答案 0 :(得分:5)
您必须将findOneByNameJoinedToVendorCategoryMappings函数放在VendorCategoryRepository类中:
<?php
namespace Test\CoreBundle\Entity;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\NoResultException;
class VendorCategoryRepository extends EntityRepository
{
public function findOneByNameJoinedToVendorCategoryMappings($vendorCategoryName)
{
$query = $this->getEntityManager()
->createQuery('
SELECT vc, vcm FROM TestCoreBundle:VendorCategory vc
JOIN vcm.vendorCategoryMapping vcm
WHERE vc.name = :name'
)->setParameter('name', $vendorCategoryName);
try
{
return $query->getSingleResult();
}
catch (NoResultException $e)
{
return null;
}
}
}
并在实体中链接此存储库类:
/**
* @ORM\Entity(repositoryClass="Test\CoreBundle\Entity\VendorCategoryRepository")
*/
class VendorCategory