Symfony 2:如何在服务中执行sql查询

时间:2015-06-29 13:23:48

标签: php symfony

上周我开始使用Symfony 2,我对如何使用模型以及如何创建自己的特定功能感到困惑。

我在services.yml文件中创建了一个服务测试

services:
testing:
class: AppBundle\Service\MyService
 arguments: [ @doctrine.orm.entity_manager ]

这是MyService类

class myService
{

/**
 * @InjectParams({
 *    "em" = @Inject("doctrine.orm.entity_manager")
 * })
 */


  public function __construct(EntityManager $em)
  {
  $this->em = $em;
  }


  function getQuery($id){
   $sql = "SELECT firstname FROM players WHERE id = $id";

    $em = $this->getDoctrine()->getManager();
    $stmt = $em->getConnection()->prepare($sql);
    $stmt->execute();
    $players = $stmt->fetchAll();
}

我想在服务中执行查询并在控制器中加载函数getQuery(),如下所示:

$locationService = $this->container->get('testing');
$ownFunction = $locationService->getQuery($id);

当我执行上面的脚本时,我收到错误。

2 个答案:

答案 0 :(得分:1)

您的getQuery方法错误。由于您已将EntityManager注入构造函数,因此您应该使用它(您的服务中没有getDoctrine方法。)

public function getQuery($id){
    $sql = "SELECT firstname FROM players WHERE id = :id";

    $stmt = $this->em->getConnection()->prepare($sql);
    $stmt->bindValue(':id', $id); //you should do this to be sql-injection safe
    $stmt->execute();

    return $stmt->fetchAll(); //you didn't return anything in your function


}

编辑:您还会错过课程顶部的use Doctrine\ORM\EntityManager;

答案 1 :(得分:0)

我认为必须是

function getQuery($id){
$sql = "SELECT firstname FROM players WHERE id = $id";

$stmt = $this->em->getConnection()->prepare($sql);
$stmt->execute();
$players = $stmt->fetchAll();

“$ em = $ this-> getDoctrine() - > getManager();”不再需要了,因为您已经将构造中的Doctrine Entity Manager注入$ this-> em。