I installed a package that has a test object that contains several testQuestion objects, each of which is a question and this answer (or 0 if there is no answer). From the branch I want to get information from the test object to say how many questions there are and how many have been answered.
I created a request to pull this from db, and in Test Entity I created 2 new properties to store the number of questions and answer to the number. I created a TestRepository inside which the request is located. The Test object checks to see if the object has a given value and if it does not load it when necessary, since I will not always need this information.
However, I was fixated on how to associate the repository code with the test object, both for calling the repo function and for the repo function, in order to store the values in the corresponding test object.
Acme / Quizbundle / Test / test.php
namespace Acme\QuizBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Acme\QuizBundle\Entity\TestRepository;
class Test {
protected $numQuestions = null;
protected $numQuestionsAnswered = null;
public function getNumQuestionsAnswered () {
if (is_null($this->numQuestionsAnswered)) {
$repository = $this->getEntityManager()->getRepository('\AcmeQuizBundle\Test');
$values = $repository->calculateNumQuestions();
}
return $this->numQuestionsAnswered;
}
Acme / Quizbundle / Test / TestRepository.php (there is a corresponding method for getNumQuestions ())
namespace Acme\QuizBundle\Entity;
use Doctrine\ORM\EntityRepository;
class TestRepository extends EntityRepository {
private function calculateNumQuestions() {
$qb = $this->getEntityManager()
->createQueryBuilder();
$query = $this->getEntityManager()->createQueryBuilder()
->select('COUNT(id)')
->from('testquestion', 'tq')
->where('tq.test_id = :id')
->setParameter('id', $this->getId())
->getQuery();
$result = $query->getSingleScalarResult();
var_dump($result);
}
source
share