Doctrine 2 createQueryBuilder具有相同的结果

时间:2015-03-17 12:40:02

标签: symfony doctrine-orm query-builder

我有两个不同的QueryBuilder,它们返回相同的结果。第一个QueryBuilder返回正确的结果。第二个QueryBuilder返回第一个结果。

问题:如何强制第二个QueryBuilder从数据库而不是从内存中获取数据?

用法:

/** @var SectionEntity $section */
foreach ( $subject->getSections() as $section ) {
    /** @var QuestionEntity $question */
    foreach ( $section->getQuestions() as $question ) {
        // ...
    }
}

这就是我调用QueryBuilders的方式:

/** @var SubjectEntity $subject */
$subject = $this->retrieveDefaultProfileQuestions();

/** @var SubjectEntity $old_subject */
$old_subject = $this->retrieveProfileQuestionsForUser( $user );

功能:

/**
 * Retrieves default profile questions from database
 *
 * @return null|SubjectEntity
 * @throws \Doctrine\ORM\NonUniqueResultException
 */
private function retrieveDefaultProfileQuestions() {
    $queryBuilder = $this->createQueryBuilder( 's' );
    $query        = $queryBuilder
        ->select( 's, sc, q' )
        ->leftJoin( 's.sections', 'sc' )
        ->leftJoin( 'sc.questions', 'q', 'WITH', 'q.user IS NULL' )
        ->where( 's.type = :TYPE' )
        ->setParameter( 'TYPE', 'profile' )
        ->getQuery();

    return $query->getOneOrNullResult();
}

/**
 * Retrieves user's profile questions from database
 *
 * @param UserEntity $user
 *
 * @return null|SubjectEntity
 * @throws \Doctrine\ORM\NonUniqueResultException
 */
private function retrieveProfileQuestionsForUser( $user ) {
    $queryBuilder = $this->createQueryBuilder( 's' );
    $query        = $queryBuilder
        ->select( 's, sc, q' )
        ->leftJoin( 's.sections', 'sc' )
        ->leftJoin( 'sc.questions', 'q', 'WITH', 'q.user = :USER' )
        ->where( 's.type = :TYPE' )
        ->setParameter( 'USER', $user )
        ->setParameter( 'TYPE', 'profile' )
        ->getQuery();

    return $query->getOneOrNullResult();
}

1 个答案:

答案 0 :(得分:0)

问题可能来自您发送给mysql的查询,它可能与之前的相同,因此在这种情况下,mysql不会构建新的execution plan并且会从内存中获得结果,有一点是我建议您尝试,将->select( 's, sc, q' )更改为->select( 's.*, sc.*, q.*' )