Symfony2 Doctrine2本机查询基础知识

时间:2015-05-18 10:34:53

标签: symfony doctrine-orm entity nativequery

我正在开发一个基本的网络应用程序。我必须使用一些sql server视图。我决定尝试本机查询,并且一旦测试了它的功能,尝试编写一些类来编写所有查询,并忘记它们的实现。

所以我的问题是,我在Acme / MyBundle / Entity / View1.php中有一个实体。 这个实体拥有与表匹配的所有属性,也是getter和setter。 我想这个实体很好地映射到了DB(Doctrine很容易使用视图)。

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

  $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?

  $returned_atts = array(
    "att1" => $result[0]->getAttribute1(), //getter from the entity 
    "att2" => $result[1]->getAttribute2(), //getter from the entity
  );

  return $returned_atts;`

1 个答案:

答案 0 :(得分:2)

如果您想将结果作为数组,则不需要使用ResultSetMapping。

$sql = " SELECT * FROM some_table";
$stmt = $this->getDoctrine()->getEntityManager()->getConnection()->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();

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

此处有更多示例Doctrine raw sql

相关问题