【问题标题】:how to write sub-query in symfony doctrine如何在 symfony 学说中编写子查询
【发布时间】:2019-07-30 09:52:20
【问题描述】:

我正在开发一个 symfony 项目,其后端是在学说和 api 平台框架中开发的。我需要获取一些详细信息以及检查另一个表中的字段,这将是一个状态。我们使用此状态在前端处理某些事情。

我试过了:-

$qb = $this->createQueryBuilder('contact');
$qb2=$qb;
$sub_query = $qb2->select('field')
    ->from('OtherTable','g')
    ->where("'id= '".$personId."'")
    ->OrderBy('updated_at', 'DESC')
    ->setMaxResults(1)
    ->getQuery()
    ->getResult();

$qb->select("contact.id, 
                contact.title, 
                count (distinct person.id) as 
number_of_contacts_with_email',(".$sub_query.") as status")
 ->leftjoin('contact.people', 'person')
 ->leftJoin('person.jobs', 'jobs')
 ->groupBy('contact.id, contact.title');


$query=$qb->getQuery();
$result = $qb->getQuery()->getArrayResult();
return $result;

执行查询时出现此错误。

  [Semantical Error] line 0, col 59 near 'OtherTable g': Error: Class 'OtherTable' is not defined.

这里怎么写这个子查询?有解决办法吗?

【问题讨论】:

  • 仍未解决,出现错误!类未定义!
  • OtherTable 实体表存在吗?
  • Othertable 实体存在,但实体未在我的查询中正确执行,我已经在存储库中包含 $injected 实体。
  • 如何在nativequery中编写整个查询,nativequery不适合我!

标签: php symfony doctrine-orm doctrine api-platform.com


【解决方案1】:

您应该简单地使用子查询的 DQL,例如:

// Don't take the query/result instances
$sub_query = $qb2->select('field')
    ->from('OtherTable','g')
    ->where("'id= '".$personId."'")
    ->OrderBy('updated_at', 'DESC')
    ->setMaxResults(1);

并使用

$qb->select("contact.id, 
                contact.title, 
                count (distinct person.id) as 
number_of_contacts_with_email',(".$sub_query->getDQL().") as status")
 ->leftjoin('contact.people', 'person')
 ->leftJoin('person.jobs', 'jobs')
 ->groupBy('contact.id, contact.title');

希望有帮助

【讨论】:

  • 嗨@Matteo 感谢您的回复,我尝试了您的解决方案,但仍然收到此错误:- [Semantical Error] line 0, col 220 near 'OtherTable g WHERE': Error: Class 'OtherTable'未定义。
  • 我发现的问题是我们不能在教义限制下运行子查询。还有其他解决方案吗?我也在检查!
  • github.com/doctrine/orm/issues/3979 所以我认为我需要在 SQL 中编写除 DQL 之外的所有查询以满足我的要求:(如果错了请纠正我!
猜你喜欢
  • 1970-01-01
  • 2013-10-07
  • 1970-01-01
  • 2011-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-28
相关资源
最近更新 更多