5

我有以下两个类,它们具有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
4

1 回答 1

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
于 2013-10-21T08:06:28.020 回答