【问题标题】:Doctrine2: query using NativeQuery and ResultSetMappingDoctrine2:使用 NativeQuery 和 ResultSetMapping 进行查询
【发布时间】:2015-03-28 00:25:50
【问题描述】:

我在自定义存储库 symfony 2 类中有这段代码,我很难理解为什么 $results 总是为空。
MyApplicationBundle:Archive 是映射到 DB 的实体类
集合是连接表 (ManyToMany) 不是实体
当前不是此类的属性,但我在结果中需要它
$where_str 是在上面构建的
我做错了什么?谢谢

    $rsm = new ResultSetMapping();
    $rsm->addEntityResult('MyApplicationBundle:Archive', 'a');
    $rsm->addFieldResult('a', 'id', 'id');
    $rsm->addFieldResult('a', 'author', 'author');
    $rsm->addFieldResult('a', 'title', 'title');
    $rsm->addFieldResult('a', 'present', 'present');

    $sql = "select
              a.id,
              a.author,
              a.title,
              IF((select c.archive_id from collection c where c.archive_id = a.id and c.user_id = :user),1,0) as present
            from
              archive a
            where
              $where_str";

    $em = $this->getEntityManager();

    $query = $em->createNativeQuery($sql, $rsm);
    $query->setParameters($arrParameters);

    $results = $query->getResult();

    return $results;

如果更好的话,非常乐意尝试使用 DQL 或 DQB。

【问题讨论】:

    标签: mysql sql symfony doctrine


    【解决方案1】:

    经过一番尝试,我发现上面的代码是正确的。我只需要在存档实体中添加字段“present”,创建 getter 和 setter(doctrine:generate:entities)并更新数据库以在表中创建字段(doctrine:schema:update --force)。不管你是否打算在其他地方使用它。

    【讨论】:

      猜你喜欢
      • 2015-02-08
      • 2012-05-28
      • 1970-01-01
      • 2012-08-25
      • 2014-01-17
      • 1970-01-01
      • 2019-12-27
      • 2013-07-26
      • 2019-10-03
      相关资源
      最近更新 更多