我希望我可以帮你似乎瘦!
如果我理解正确,您希望从数据库为每个对象实例加载除了此对象的所有字段之外的子对象的数量 - 作为附加字段。对?
我不知道,您的模型中父实体和子实体是如何命名的。但我会从我的Web应用程序为您的任务提供一个工作示例。您只需重命名父和子实体。
有联盟计划,其中每个在我的应用程序中都有一组有限的帐户。所以,我有一个名为'AffiliateProgram'的父实体,我有一个名为'AffiliateProgramAccount'的子实体。
您不应该覆盖存储库中实体类的标准方法。您只需根据需要添加您的方法。
首先,为您的父实体的类(How to Create custom Repository Classes)创建一个存储库。我这样做是在YAML文件,描述如下:
Analytics\TrafficStatisticsBundle\Entity\AffiliateProgram:
type: entity
table: affiliate_program
repositoryClass: Analytics\TrafficStatisticsBundle\Entity\AffiliateProgramRepository
然后,你必须根据教义中描述的路径创建一个存储库类的父实体。我在“实体”目录中将模型类放在一起。现在您可以根据您的个人需求在创建的存储库中创建自定义方法。
我建议使用Doctrine DBAL来解决您的问题(How to use Doctrine DBAL)。这里是我的查询的例子,完全等同于你:
use Doctrine\ORM\EntityRepository;
class AffiliateProgramRepository extends EntityRepository {
/**
* @return array
* @throws \Doctrine\DBAL\DBALException
*/
public function findAllAffiliatePrograms() {
// $stmt = $this->getEntityManager()
// ->getConnection()
// ->prepare('
// SELECT COUNT(apa.id) AS Number_of_accounts, ap.*
// FROM affiliate_program AS ap
// LEFT JOIN affiliate_program_account AS apa ON apa.affiliate_program_id = ap.id
// GROUP BY ap.id');
// $stmt->execute();
// return $stmt->fetchAll();
$stmt = $this->getEntityManager()
->getConnection()
->prepare('
SELECT COUNT(apa.id) AS Number_of_accounts, ap.*
FROM affiliate_program AS ap,
affiliate_program_account AS apa
WHERE apa.affiliate_program_id = ap.id
GROUP BY ap.id');
$stmt->execute();
return $stmt->fetchAll();
}
}
这里发现我不使用对象名称(:在我的情况“AnalyticsTrafficStatisticsBundle AffiliateProgram”)为运营商FROM,[左|正确| INNER | OUTER] JOIN,因为它必须在DQL中使用,而我使用的是真正的表名。 注意:不使用JOIN运算符的查询执行速度更快。在我的例子中,我展示了两种方法 - 使用JOIN运算符,以及使用WHERE运算符。证明: 和
现在,你可以得到所有的对象根据控制器查询,只需调用新创建的方法:
<?php
namespace Testing\TestBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
/**
* TestController
*
* @Route("/test")
*/
class TestController extends Controller {
/**
* @Route("/", name="test_index")
* @Method("GET")
*/
public function indexAction() {
$em = $this->getDoctrine()->getManager();
$affiliatePrograms = $em->getRepository('AnalyticsTrafficStatisticsBundle:AffiliateProgram')->findAllAffiliatePrograms();
return $this->render('TestingTestBundle:Test:test.html.twig', [
'result' => $affiliatePrograms
]);
}
}
,并确保一切正常,你只需写下面的代码片段即可。小枝文件(例如):
{{ dump(result) }}
材料也,在这里看到:
- How to use Raw SQL Queries in Symfony 2
- Raw SQL Queries
- Executing SQL directly in Symfony2 Doctrine
我希望这是你所需要的!
你的问题对我来说还不清楚。寻呼机与你的问题有什么关系?你的问题不是用[自定义DQL查询]解决的(http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html)? –
是的,我明白我需要一个自定义的SQL查询,但我无法找到我的存储库中的函数来挂钩它。如果我重写findBy,我该如何传递我的分页参数。 – jdog
'$ this-> getEntityManager() - > createQuery($ dql);'。其中'$ dql'是一个DQL字符串。 –