在Doctrine中查询连接表

时间:2013-10-21 04:50:54

标签: symfony doctrine-orm

我有以下两个具有 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

1 个答案:

答案 0 :(得分:10)

首先,我建议使用注释,您的代码将更加可读

我认为问题是您忘记了inversedBymappedBy属性。

以下代码是使用注释解决问题的可能方法。

您应该将此代码添加到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