原则:在其他表

在INSERT,UPDATE专栏中,我有2个实体:服务和会话与一个一对多的关系原则:在其他

class Service{ 

/**

* @var int

*

* @ORM\Column(name="avg_score", type="integer")

*/

private $avgScore;

/**

* @ORM\OneToMany(targetEntity="Session", mappedBy="service")

*/

private $sessionList;

}

class Session{

/**

* @ORM\ManyToOne(targetEntity="Service", inversedBy="sessionList")

* @ORM\JoinColumn(name="service_id", referencedColumnName="id")

*/

private $service;

/**

* @var int

*

* @ORM\Column(name="score", type="integer", nullable=true)

*/

private $score;

}

教义的QueryBuilder我怎么可以更新Service实体每次新Session$score$avgScore被建造?

这就是我试图做的:

$qb = $this->getDoctrine()->getEntityManager()->createQueryBuilder(); 

$q = $qb->update('AppBundle:Service', 's')

->join('AppBundle:Session', 'ss')

->addSelect('avg(ss.score) as score_avg')

->groupBy('ss.service')

->set('s.avgScore', 'score_avg')

->where('s.id = ?1')

->setParameter(1, $service->getId())

->getQuery();

$q->execute();

回答:

你需要创建一个Doctrine Events Listener

services: 

my.listener:

class: AppBundle\EventListener\AvgScoreUpdater

tags:

- { name: doctrine.event_listener, event: prePersist }

然后在AvgScoreUpdater实现逻辑:

class AvgScoreUpdater 

{

public function prePersist(LifecycleEventArgs $args)

{

$entity = $args->getEntity();

if (!($entity instanceof Session) || !$entity->getScore()) {

return;

}

$entityManager = $args->getEntityManager();

$service = $entity->getService();

// Then realize logic to update avg_score on a service

}

}

以上是 原则:在其他表 的全部内容, 来源链接: utcz.com/qa/257221.html

回到顶部