Symfony2 Doctrine2 原生查询基础

3
我在工作中正在开发一个基本的Web应用程序。我需要与一些SQL Server视图一起工作。我决定尝试使用本地查询,并且一旦测试其功能,就会编写一些类以编码所有查询并忘记它们的实现。
所以我的问题是,在Acme / MyBundle / Entity / View1.php中有一个实体。这个实体具有与表匹配的所有属性以及它们的getter和setter。我猜想这个实体已经被很好地映射到数据库中(Doctrine无法轻松地使用视图)。
我的目标是让控制器能够从这些视图(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、attribute2和attribute3?

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

  return $returned_atts;`
1个回答

5
如果您想要将结果作为数组返回,就不需要使用ResultSetMapping。
$sql = " SELECT * FROM some_table";
$stmt = $this->getDoctrine()->getEntityManager()->getConnection()->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();

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

更多示例请参见Doctrine原始SQL


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接