>我有如下所示的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 ▶}
]
如您所见,它重复同一行。
代码有什么问题?
如果你只想要一个结果,你可以使用->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
的一个例子。