多年后,但可能会有所帮助。
是的 ]
如果您需要/想要/必须,您可以使用Querybuilder执行具有子选择语句的更新查询,而不是直接使用底层连接层。
这里的想法是使用 QueryBuilder 两次。
- 构建一个 select 语句来计算新值。
- 构建实际的更新查询以提交到数据库,您将在其中注入前一个 select DQL,正如您所期望的那样,以发出单个数据库请求。
例子 ]
给定一个用户可以出售对象的应用程序。每笔交易都涉及买方和卖方。交易结束后,卖家和买家可以对交易如何与对方进行评论。
您可能需要一个User表、一个Review表和一个Transaction表。
User 表包含一个名为rating的字段,它将保存用户的平均评分。Review 表存储一个事务 id、作者 id(提交评论的人)、一个值(从 0 到 5)。最后,交易包含买卖双方的参考。
现在假设您想在对方提交评论后更新用户的平均评分。更新查询将计算用户的平均评分并将结果作为User.rating
属性的值。
我将以下代码段与Doctrine 2.5和Symfony3 一起使用。updateRating( User $user)
因为这项工作是关于用户的,所以我在AppBundle\Entity\UserRepository.php存储库中创建一个新的公共函数是有意义的。
/**
* Update the average rating for a user
* @param User $user The user entity object target
*/
public function updateRating( User $user )
{
// Compute Subrequest. The reference table being Transaction, we get its repository first.
$transactionRepo = $this->_em->getRepository('AppBundle:Transaction');
$tqb = $postRepo->createQueryBuilder('t');
#1 Computing select
$select = $tqb->select('SUM(r.value)/count(r.value)')
// My Review table as no association declared inside annotation (because I do not need it elsewhere)
// So I need to specify the glue part in order join the two tables
->leftJoin('AppBundle:Review','r', Expr\Join::WITH, 'r.post = p.id AND r.author <> :author')
// In case you have an association declared inside the Transaction entity schema, simply replace the above leftJoin with something like
// ->leftJoin(t.reviews, 'r')
// Specify index first (Transaction has been declared as terminated)
->where( $tqb->expr()->eq('t.ended', ':ended') )
// The user can be seller or buyer
->andWhere( $tqb->expr()->orX(
$tqb->expr()->eq('t.seller', ':author'),
$tqb->expr()->eq('t.buyer', ':author')
));
#2 The actual update query, containing the above sub-request
$update = $this->createQueryBuilder('u')
// We want to update a row
->update()
// Setting the new value using the above sub-request
->set('u.rating', '('. $select->getQuery()->getDQL() .')')
// should apply to the user we want
->where('u.id = :author')
// Set parameters for both the main & sub queries
->setParameters([ 'ended' => 1, 'author' => $user->getId() ]);
// Get the update success status
return $update->getQuery()->getSingleScalarResult();
}
现在从控制器
// … Update User's rating
$em->getRepository('AppBundle:User')->updateRating($member);
// …