Symfony2 queryBuilder为什么数组重复每个字段

时间:2015-04-18 06:29:21

标签: php arrays symfony doctrine-orm dql

我有如下所示的queryBuilder,并希望按给定日期检索数据。它有效,但不是我想要的。它返回包含11个项目(表中的字段数)的数组,而不是仅返回一个。

PHP

$query = $queryBuilder->select(array('menu'))
    ->from('InfoMenuBundle:Menu', 'menu')
    ->where("menu.date = :date")
    ->setParameter('date', $date)
    ->getQuery();
$entity = $query->getResult();

输出

    array:11 [▼
  0 => Menu {#533 ▼
    -id: 1
    -date: "2015-04-01"
    -food1: "Ezogelin Çorbası"
    -calories1: "217"
    -food2: "Etli Nohut"
    -calories2: "395"
    -food3: "Şehriyeli Pirinç Pilavı"
    -calories3: "342"
    -food4: "Mevsim Salatası"
    -calories4: "180"
    -other: "Ekmek (1 Dilim)"
    -calories5: "80"
    -totalCalories: "1134"
  }
  1 => Menu {#538 ▼
    -id: 31
    -date: "2015-04-01"
    -food1: "Ezogelin Çorbası"
    -calories1: "217"
    -food2: "Etli Nohut"
    -calories2: "395"
    -food3: "Şehriyeli Pirinç Pilavı"
    -calories3: "342"
    -food4: "Mevsim Salatası"
    -calories4: "180"
    -other: "Ekmek (1 Dilim)"
    -calories5: "80"
    -totalCalories: "1134"
  }
  2 => Menu {#536 ▶}
  3 => Menu {#537 ▶}
  4 => Menu {#534 ▶}
  5 => Menu {#531 ▶}
  6 => Menu {#530 ▶}
  7 => Menu {#529 ▶}
  8 => Menu {#495 ▶}
  9 => Menu {#543 ▶}
  10 => Menu {#544 ▶}
]

如你所见,重复同一行。

代码有什么问题?

1 个答案:

答案 0 :(得分:0)

如果您只想要一个结果,则可以使用->getSingleResult()代替->getResult()和一个名为setMaxResults的函数

然后,您应该首先订购行,您可以使用->orderBy([field], [direction])。你需要提出一个与你最相关的标准。

完整示例:

$query = $queryBuilder
    ->select(array('menu'))
    ->from('InfoMenuBundle:Menu', 'menu')
    ->where("menu.date = :date")
    ->setParameter('date', $date)
    ->orderBy('menu.date', 'asc')
    ->setMaxResults(1)
    ->getQuery()
;
$entity = $query->getSingleResult(); // getSingleResult hydrates to object instead of an ArrayCollection.

如果一切顺利,$entity现在将成为InfoMenuBundle:Menu的实例。