首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Symfony2 Doctrine2本机查询基础知识

Symfony2 Doctrine2本机查询基础知识
EN

Stack Overflow用户
提问于 2015-05-18 18:34:53
回答 1查看 6.9K关注 0票数 3

我正在开发一个基本的网络应用程序在我的工作。我必须使用一些sql服务器视图。我决定尝试原生查询,一旦测试了它的功能,就试着编写一些类来编写所有查询的代码,然后有点忘记了它们的实现。

所以我的问题是,我在Acme/MyBundle/ Entity /View1.php中有一个实体。这个实体已经获得了与表匹配的所有属性以及它的getter和setter。我猜这个实体很好地映射到了数据库(Doctrine不能很容易地与视图一起工作)。

我的目标是让Controller能够从这些视图(SQL SERVER)中获取一些数据,并将其返回给视图(twig),这样它就可以显示信息。

代码语言:javascript
复制
  $returned_atts = array(
    "att1" => $result[0]->getAttribute1(), //getter from the entity
    "att2" => $result[1]->getAttribute2(), //getter from the entity
  );

  return $returned_atts;`$sql = "SELECT [Attribute1],[Attribute2],[Attribute3] FROM [TEST].[dbo].[TEST_VIEW1]"; //THIS IS THE SQL SERVER QUERY
  $rsm = new ResultSetMapping($em); //result set mappin object
  $rsm->addEntityResult('Acme\MyBundle\Entity\View1', 'view1'); //entity which is based on
  $rsm->addFieldResult('view1', 'Attribute1', 'attribute1'); //only choose these 3 attributes among the whole available
  $rsm->addFieldResult('view1', 'Attribute2', 'attribute2');
  $rsm->addFieldResult('view1', 'Attribute3', 'attribute3');
  //rsm built
  $query = $em->createNativeQuery($sql, $rsm); //execute the query
  $result = $query->getResult(); //get the array

应该可以直接从getResult()方法返回数组,不是吗?最让我头疼的是,我怎么才能访问attribute1、attriute2和attriute2?

代码语言:javascript
复制
  $returned_atts = array(
    "att1" => $result[0]->getAttribute1(), //getter from the entity 
    "att2" => $result[1]->getAttribute2(), //getter from the entity
  );

  return $returned_atts;`
EN

回答 1

Stack Overflow用户

发布于 2015-05-18 22:39:12

如果希望结果为数组,则不需要使用ResultSetMapping。

代码语言:javascript
复制
$sql = " SELECT * FROM some_table";
$stmt = $this->getDoctrine()->getEntityManager()->getConnection()->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();

这是控制器操作的一个基本示例。您可以转储结果,使用var_dump()查看如何访问特定的字段值。

这里有更多的例子Doctrine raw sql

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30300919

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档