我有一个SQL查询返回一个表(国家/地区)中的所有行,这些表在另一个表(ducks)中有相关条目,但我很难将其转换为DQL。这是一个标准的一对多关系,因为每个国家可以有多个鸭子,我相信它都是正确设置的,因为我可以在一个国家内返回鸭子并使用标准代码返回该国家。
工作查询是:
SELECT c.* FROM country c
INNER JOIN ducks d
ON c.id = d.country_id
GROUP BY c.country
ORDER BY c.country ASC
我尝试将其转换为:
SELECT c FROM WfukDuckBundle:Country c
INNER JOIN WfukDuckBundle:Ducks d
ON c.id = d.country_id
GROUP BY c.country
ORDER BY c.country ASC
会产生以下错误:
[Semantical Error] line 0, col 79 near 'd ON': Error: Identification Variable
WfukDuckBundle:Ducks used in join path expression but was not defined before.
我对Symfony / Doctrine很新,所以我怀疑它可能是显而易见的!
我正在使用Symfony 2.0.11和doctrine
更新: 我也试过了:
SELECT c FROM WfukDuckBundle:Country c
INNER JOIN c.ducks d
ON c.id = d.country_id
GROUP BY c.country
ORDER BY c.country ASC
其中'ducks'在Country类中定义为:
/**
* @ORM\OneToMany(targetEntity="Ducks", mappedBy="country")
*/
protected $ducks;
public function __construct()
{
$this->ducks = new ArrayCollection();
}
ducks类中国家的定义是:
/**
* @ORM\ManyToOne(targetEntity="Country", inversedBy="ducks")
* @ORM\JoinColumn(name="country_id", referencedColumnName="id")
*/
private $country;
答案 0 :(得分:5)
帮自己一个忙,并使用查询构建器。更易于阅读,更新和重复使用您的查询
<?php
namespace Vendor\Prefix\Repository;
use Doctrine\ORM\EntityRepository;
class SomeRepository extends EntityRepository
{
public function countryDucks()
{
// $em is the entity manager
$qb = $em->createQueryBuilder();
$qb
->select('country', 'duck')
->from('WfukDuckBundle:Country', 'country')
->innerJoin('country.ducks', 'duck')
->groupBy('country.country')
->orderBy('country.country', 'ASC')
;
$query = $qb->getQuery();
// Potential Hydration Modes
// --------------------------------
// Doctrine\ORM\Query::HYDRATE_OBJECT
// Will give you an array of your object entities
// --------------------------------
// Doctrine\ORM\Query::HYDRATE_ARRAY
// Will give you an array mimicking
// your object graph
// --------------------------------
return $query->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);
}
}