我想得到与另一个实体相关联的实体的字段。
我的实体提供有一个last_offer字段。报盘与产品实体有关。
然后,通过在实体产品中进行咨询,我想获得与实体报价相关的最新报价。
主计长:
public function lastAction($key)
{
$em = $this->getDoctrine()->getManager();
$last_offer = $em->getRepository('MyAppBundle:Products')->findOfferByKey($key);
$response = new JsonResponse();
return $response->setData($last_offer);
}我的存储库:
public function findOfferByKey($key){
$em = $this->getEntityManager();
$dql = 'SELECT pr, of FROM MyAppBundle\AppBundle\Entity\Products pr
INNER JOIN pr.offers of
WHERE pr.key = :key';
$query = $this->getEntityManager()
->createQuery($dql)
->setParameter('key', $key)
->setHydrationMode(\Doctrine\ORM\Query::HYDRATE_ARRAY);
return $query->execute();
}我的路线:
last_offer:
path: /{key}/last_offer
defaults: { _controller: "MyAppBundle:Products:last" }但是,这会返回一个数组。
我只想返回last_offer元素。
或者返回实体所提供的而不存在于数组中。
发布于 2015-05-27 18:25:38
你特别告诉原则用这一行生成/返回数组
->setHydrationMode(\Doctrine\ORM\Query::HYDRATE_ARRAY);我认为你所需要做的就是删除这条线,教义将生成/返回实体。但是,您将得到一个集合,所以请确保考虑到这一点。也许就像
public function findOfferByKey($key) {
$dql = 'SELECT pr, of FROM MyAppBundle\AppBundle\Entity\Products pr
INNER JOIN pr.offers of
WHERE pr.key = :key';
$query = $this->getEntityManager()
->createQuery($dql)
->setParameter('key', $key)
;
$results = $query->execute();
if (count($results) !== 1)
{
// It's up to you how to handle zero or multiple rows
}
return $results->current();
}编辑
我知道发生了什么-我没有注意到你的SELECT卡。您不仅选择了last_offer列,还选择了和 Products实体= $results的全部产品,它们将是所有这些内容的数组。在这个场景中,$query->execute()将返回一个array()而不是一个集合。
如果只想选择Offer实体,则需要修改select
$dql = 'SELECT of
FROM MyAppBundle\AppBundle\Entity\Products pr
INNER JOIN pr.offers of
WHERE pr.key = :key';但要小心,这可能还会有不止一场争吵。
https://stackoverflow.com/questions/30490233
复制相似问题