我有以下两个具有 ManyToMany 关系的类,并保存在名为countries_involved
的连接表中。
class CountriesInvolved
{
/**
* @var integer
*/
private $id;
/**
* @var string
*/
private $description;
/**
* @var \DateTime
*/
private $createdAt;
/**
* @var \DateTime
*/
private $updatedAt;
/**
* @var \ACME\SouthBundle\Entity\Country
*/
private $country;
/**
* @var \Doctrine\Common\Collections\Collection
*/
private $involvement;
}
和
class Involvement
{
/**
* @var integer
*/
private $id;
/**
* @var string
*/
private $name;
/**
* @var string
*/
private $description;
}
关系在YML中定义如下
manyToMany:
involvement:
targetEntity: Involvement
joinTable:
name: countries_involvement
joinColumns:
case_country_involved_id:
referencedColumnName: id
inverseJoinColumns:
involvement_id:
referencedColumnName: id
我试图根据参与的ID返回所涉及的国家/地区的结果,但是在编写查询时却没有出现错误。这是我到目前为止所尝试的内容:
$em = $this->getDoctrine()->getManager()->createQueryBuilder();
$q = $em->select('c')
->from('ACMESouthBundle:CountriesInvolved','c')
->innerJOIN('c.Involvement','i')
->where('i.id = 1')
->groupBy('c.country')->getQuery();
错误是:
[Semantical Error] line 0, col 80 near 'i WHERE i.id': Error: Class ACME\SouthBundle\Entity\CountriesInvolved has no association named Involvement
答案 0 :(得分:10)
首先,我建议使用注释,您的代码将更加可读。
我认为问题是您忘记了inversedBy
和mappedBy
属性。
以下代码是使用注释解决问题的可能方法。
您应该将此代码添加到Involvement
实体:
/**
* @ORM\ManyToMany(targetEntity="CountriesInvolved", inversedBy="involvement")
* @ORM\JoinTable(name="countries_involvement",
* joinColumns={@ORM\JoinColumn(name="case_country_involved_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="involvement_id", referencedColumnName="id")}
* )
*/
private $countries;
并在CountriesInvolved
实体中,您应在$involvement
中添加以下注释:
/**
* @ORM\ManyToMany(targetEntity="Involvement", mappedBy="countries")
*/
private $involvement;
我刚刚重写了这样的查询:
$em = $this->getEntityManager();
$query = $em->createQuery('
SELECT c
FROM ACMESouthBundle:CountriesInvolved c
JOIN c.involvement i
WHERE i.id = :id
');
$query->setParameter('id', '1');
return $query->getResult();
这是使用YAML方法:
CountriesInvolved:
manyToMany:
involvement:
targetEntity: Involvement
mappedBy: countries
CountriesInvolved:
manyToMany:
countries:
targetEntity: CountriesInvolved
inversedBy: involvement
joinTable:
name: countries_involvement
joinColumns:
case_country_involved_id:
referencedColumnName: id
inverseJoinColumns:
involvement_id:
referencedColumnName: id