我有3个实体:主题,章节,问题。每个人都与其他人有关系。我想了解当前$user
的问题。如果没有,我会使用user = NULL
复制默认值。
但是,教条让我很头疼。最初它不会得到null用户的问题。现在,在刷新数据库中的新问题之后,它就不会得到它们(它们被正确插入)。
可能有一些我看不到的东西。
为什么不能检索新问题?
<?php
public function getProfileQuestionsForUser( $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();
$sql = $query->getSQL();
/** @var SubjectEntity $result */
$result = $query->getOneOrNullResult();
$hasQuestions = false;
foreach ( $result->getSections() as $section ) {
$qs = count($section->getQuestions());
if ( count( $section->getQuestions() ) ) {
$hasQuestions = true;
break;
}
}
if ( $hasQuestions == false ) {
$queryBuilder = $this->createQueryBuilder( 's' );
$query = $queryBuilder
->select( 's, q, sc' )
->leftJoin( 's.sections', 'sc' )
->leftJoin( 's.questions', 'q', 'WITH', 'q.user IS NULL' )
->where( 's.type = :TYPE' )
->setParameter( 'TYPE', 'profile' )
->getQuery();
$sql = $query->getSQL();
/** @var SubjectEntity $subject */
$subject = $query->getOneOrNullResult();
if ( ! empty( $subject ) ) {
/** @var QuestionEntity $question */
$qs = count( $subject->getQuestions() );
foreach ( $subject->getQuestions() as $question ) {
$new_question = clone $question;
$new_question->setUser( $user );
$new_question->setAnswers( new ArrayCollection() );
$new_question->setQuestionStatuses( new ArrayCollection() );
$new_question->setOptions( new ArrayCollection() );
$this->getEntityManager()->persist( $new_question );
}
$this->getEntityManager()->flush();
// Retrieve new questions from DB
$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();
$sql = $query->getSQL();
$result = $query->getOneOrNullResult();
}
}
return $result;
}
答案 0 :(得分:2)
也许这样的事情会起作用:
//In your Question entity add this
public function __clone() {
$this->id = null;
}
并修改你的代码:
foreach ( $subject->getQuestions() as $question ) {
$new_question = clone $question;
$this->getEntityManager()->detach($new_question);
$new_question->setUser( $user );
$new_question->setAnswers( new ArrayCollection() );
$new_question->setQuestionStatuses( new ArrayCollection() );
$new_question->setOptions( new ArrayCollection() );
$this->getEntityManager()->persist( $new_question );
}
$this->getEntityManager()->flush();
嗯,这里有一个more complete answer