php 对象 数量,php – Symfony2 / Doctrine如何在实体中存储相关对象的数量
我已經(jīng)設(shè)置了一個(gè)包含測(cè)試對(duì)象的包,該對(duì)象包含許多testQuestion對(duì)象,每個(gè)對(duì)象都是一個(gè)問(wèn)題和給定的答案(如果沒(méi)有答案則為0).從樹枝上我希望能夠從測(cè)試對(duì)象中獲取信息,說(shuō)明有多少問(wèn)題以及已經(jīng)回答了多少問(wèn)題.
我創(chuàng)建了一個(gè)查詢來(lái)將其從數(shù)據(jù)庫(kù)中拉出來(lái),在測(cè)試實(shí)體中我創(chuàng)建了2個(gè)新屬性來(lái)存儲(chǔ)問(wèn)題的數(shù)量和回答的數(shù)量.我創(chuàng)建了一個(gè)查詢所在的TestRepository. Test對(duì)象檢查對(duì)象是否設(shè)置了值,如果沒(méi)有,則在需要時(shí)加載它,因?yàn)槲也豢偸切枰@些信息.
但是我仍然堅(jiān)持如何將存儲(chǔ)庫(kù)代碼鏈接到測(cè)試對(duì)象,既調(diào)用repo函數(shù)又調(diào)用repo函數(shù)將值保存到相關(guān)的Test對(duì)象.
ACME / Quizbundle /測(cè)試/ 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(有一個(gè)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如何在实体中存储相关对象的数量的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 威力之路
- 下一篇: Java技术:实现pdf和Excel的生