在doctrine查询构建器中实现连接无法正常工作

时间:2017-09-19 14:17:06

标签: mysql symfony doctrine-orm

我试图根据另一个表中的信息从一个表中获取信息,该表由ID链接。

这两个表格是:propertyunit

我需要收集属性中的所有单位,但仅当属性的状态为“1”且隐藏标志为“0”时才需要。在正常的mySQL中,我写道:

SELECT u.* FROM unit u INNER JOIN property p ON p.id = u.property WHERE p.status = 1 AND p.hidden = 0

产生正确的结果,尽管当我使用querybuilder尝试相同的时候:

$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select('u')
    ->from('AppBundle:Unit', 'u')
    ->join('u', 'AppBundle:Property', 'p', 'u.property = p.id')
    ->where('p.status = :status')
    ->andWhere('p.hidden = :hidden')
    ->setParameter('status', 1)
    ->setParameter('hidden', 0);

return $qb->getQuery()->getResult();

使用从Doctrine Query Builder文档中收集的信息。但是,当我加载页面时,我收到以下错误:

  

[语义错误]第0行,第42行'u AppBundle:Property':错误:   “u”类未定义。

正在执行的查询:

SELECT u FROM AppBundle:Unit u INNER JOIN u AppBundle:Property P u.property = p.id WHERE p.status = :status AND p.hidden = :hidden

任何人都可以在我的查询中帮助弄清楚我做错了吗?

2 个答案:

答案 0 :(得分:2)

尝试改变这个:

->join('u', 'AppBundle:Property', 'p', 'u.property = p.id')

到此:

->join('AppBundle:Property', 'p', 'WITH', 'u.property = p.id')

答案 1 :(得分:0)

您应该交换第一个和第二个参数位置,因为join()方法是:

/**
 * Creates and adds a join over an entity association to the query.
 *
 * The entities in the joined association will be fetched as part of the query
 * result if the alias used for the joined association is placed in the select
 * expressions.
 *
 * <code>
 *     $qb = $em->createQueryBuilder()
 *         ->select('u')
 *         ->from('User', 'u')
 *         ->join('u.Phonenumbers', 'p', Expr\Join::WITH, 'p.is_primary = 1');
 * </code>
 *
 * @param string      $join          The relationship to join.
 * @param string      $alias         The alias of the join.
 * @param string|null $conditionType The condition type constant. Either ON or WITH.
 * @param string|null $condition     The condition for the join.
 * @param string|null $indexBy       The index for the join.
 *
 * @return QueryBuilder This QueryBuilder instance.
 */
public function join($join, $alias, $conditionType = null, $condition = null, $indexBy = null)

这是一个来自Doctrine QueryBuilder类的文档。