使用来自Controller中的查询数据

时间:2017-05-24 16:26:02

标签: symfony doctrine-orm query-builder

我可以在Symfony3项目中将哪些内容更改为Doctrine正确接收的数据?

当我用 - > MyQuery($ selName)替换-> findOneBy ('name' => $selName)时,我会收到FatalThrowableError

“在阵列500内部服务器错误上调用成员函数getName()” line:

- > setGoalName($ dictSelRow-> getName())

但是如果使用 findOneBy 就可以。

存储库:

class DictSelRepository extends EntityRepository
{
  /**
   * Function MyQuery
   * @param $selName
   *
   * @return array
   */
  public function MyQuery( $selName )
  {
    return $this->createQueryBuilder( 'dg' )
      ->where( 'dg.name= :par1' )
      ->andWhere( 'dg.dateStart >= :now')
      ->andWhere( 'dg.dateEnd < :now')
      ->setParameter( 'par1', $selName )
      ->setParameter( 'now', new \DateTime() )
      ->getQuery()
      ->setMaxResults(1)
      ->getResult();
  }
}

来自控制器

/**
 * Creates a new SeluRF entity.
 *
 * @Route("/new", name="selu_new")
 * @Method({"GET", "POST"})
 *
 *
 * @Template
 */
public function newSeluRFAction( Request $request)
{
    $em = $this->getDoctrine()->getRepository( 'MyBundle:SeluRF' );
    $dictSelRow = $em
        // ->findOneBy( [ 'name' => 'X127a',]);
        ->dictGoalByTypeQuery( '1w' );

    $SeluRF = new SeluRF();
    $SeluRF
        ->setGoalName ($dictSelRow->getName())
        ->setGoalType ($dictSelRow->getType())
        ->setDateStart($dictSelRow->getDateStart())
        ->setDateEnd  ($dictSelRow->getDateEnd())
        ->setSymbolName($dictSelRow->getSymbolName())
    ;

    $form = $this->createForm('MyBundle\Form\SeluType', $SeluRF);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($SeluRF);
        $em->flush();

        return $this->redirectToRoute('selu_show', ['id' => $SeluRF->getId()]);
    }

    return [
        'SeluRF' => $SeluRF,
        'form'    => $form->createView(),
    ];
}

1 个答案:

答案 0 :(得分:2)

如果您不希望您的函数返回一个数组但只有一个实体,请使用getSingleResult

class DictSelRepository extends EntityRepository
{
  /**
   * Function MyQuery
   * @param $selName
   *
   * @return array
   */
  public function MyQuery( $selName )
  {
    return $this->createQueryBuilder( 'dg' )
      ->where( 'dg.name= :par1' )
      ->andWhere( 'dg.dateStart >= :now') // This should probably be <= ?
      ->andWhere( 'dg.dateEnd < :now') // This should probably be > (or >=) ?
      ->setParameter( 'par1', $selName )
      ->setParameter( 'now', new \DateTime() )
      ->getQuery()
      ->getSingleResult(); // Replaced getResult with getSingleResult
  }
}