php 对象 数量,php – Symfony2 / Doctrine如何在实体中存储相关对象的数量
我已經(jīng)設(shè)置了一個包含測試對象的包,該對象包含許多testQuestion對象,每個對象都是一個問題和給定的答案(如果沒有答案則為0).從樹枝上我希望能夠從測試對象中獲取信息,說明有多少問題以及已經(jīng)回答了多少問題.
我創(chuàng)建了一個查詢來將其從數(shù)據(jù)庫中拉出來,在測試實體中我創(chuàng)建了2個新屬性來存儲問題的數(shù)量和回答的數(shù)量.我創(chuàng)建了一個查詢所在的TestRepository. Test對象檢查對象是否設(shè)置了值,如果沒有,則在需要時加載它,因為我不總是需要這些信息.
但是我仍然堅持如何將存儲庫代碼鏈接到測試對象,既調(diào)用repo函數(shù)又調(diào)用repo函數(shù)將值保存到相關(guān)的Test對象.
ACME / Quizbundle /測試/ test.php的
namespace Acme\QuizBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Acme\QuizBundle\Entity\TestRepository;
/**
* @ORM\Entity(repositoryClass="Acme\QuizBundle\Entity\TestRepository")
* @ORM\Table(name="test")
*/
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(有一個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);
}
總結(jié)
以上是生活随笔為你收集整理的php 对象 数量,php – Symfony2 / Doctrine如何在实体中存储相关对象的数量的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 威力之路
- 下一篇: php 5.4 aws,使用 Amazo