mysql - Doctrine 和 symfony2 中的多个更新查询

标签 mysql symfony doctrine

我尝试过多种方法来做到这一点,但我找不到它工作的确切语法。我的最新尝试如下(在 Symfony2 实体存储库类中):

public function updateOrdering($new_order, $evaluation_id)
{
    $qb = $this->createQueryBuilder('IddpRplusBundle:Answer');
    foreach($new_order as $item){
        $id = $item['id'];
        $answernr = $item['answernr'];
        $q = $qb->update('IddpRplusBundle:Answer a')
                ->set('a.answernr', $answernr)
                ->where('a.id = :id')
                ->getQuery()
                ->execute()
                ;
    }
}

错误是“无效的参数数量:绑定(bind)变量的数量与标记的数量不匹配”。我还想添加第二个where子句

->where('a.evaluation_id = :evaluation_id')

这是mysql表中的外键,但随后错误更改为“找不到evaluation_id字段”,即使它存在于表本身中(评估和答案实体之间的关系是一对多,并且已映射在实体中也是如此)

有什么想法吗?

[更新]

下面的解决方案中有一个问题。我还必须添加对刷新的调用,否则它将开始累积更新字段,如“更新答案集answernr = 1,answernr = 2,其中id = 2”。所以最终的解决方案是:

->set('a.answernr', (int)$answernr + (int)$start)
->where('a.id = :id AND a.evaluation = :evaluation_id ')
                ->setParameters(array('id' => $id,'evaluation_id' => $evaluation_id))
                ->getQuery()
                ->execute()
                ;
        $this->_em->flush();

最佳答案

您正在为 id 设置变量,但在执行查询之前未将其绑定(bind)到值。

固定代码:

public function updateOrdering($new_order, $evaluation_id)
{
    $qb = $this->createQueryBuilder('IddpRplusBundle:Answer');
    foreach($new_order as $item){
        $id = $item['id'];
        $answernr = $item['answernr'];
        $q = $qb->update('IddpRplusBundle:Answer a')
            ->set('a.answernr', $answernr)
            ->where('a.id = :id')
            ->setParameter('id', $id)
            ->getQuery()
            ->execute();
    }
}

至于您的“evaluation_id”字段,请检查实体类中的名称,在 DQL 中编写查询时需要使用字段名称,而不是列名称。

关于mysql - Doctrine 和 symfony2 中的多个更新查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10405467/

相关文章:

php - 转换为 postgres 后 Yii Rights 模块错误

symfony1 - 使用 sfDoctrineGuardPlugin 的 schema.yml

unit-testing - 单元测试自定义 Doctrine 存储库

php - 从 SQL 数组中检索所有数据(类似于给定值)

php - Laravel 上的 mysql SQLSTATE[23000] 错误

mysql - 如何在mysql中获取父级同一表中的子级行

php - 为什么总是调用 symfony2 安全选民?

php - 如何测试对象是否持久保存在数据库 Symfony/PHPUnit 中

symfony - 如何定义附加邮件服务以使用假脱机并在 Symfony2 中发送即时电子邮件

validation - Symfony2+Doctrine - 验证实体的一对多集合