Symfony2,如何显示来自具有多对多关联的实体的数据

Symfony2, how to display data from entities with ManyToMany associations

我有多个通过 ManyToMany 和 ManyToOne 关联关联的实体,我在显示关联中超过一层的数据时遇到问题

例如。连接了 3 个实体。客户->地址->国家。在 TWIG 中我可以显示:

{{ customer.name }} // outputs name
{{ customer.address.postcode }} // outputs post code from Address entity

但是这个:

{{ customer.address.country.isocode2 }} //should output ISO code from country entity

输出 500 内部服务器错误:

Method "isocode2" for object "Doctrine\ORM\PersistentCollection" does not exist in AppBundle:tables:customers.html.twig at line 43

更多信息 客户实体,地址映射

/**
 * @var \AppBundle\Entity\Address
 *
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Address")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="defaultaddress_id", referencedColumnName="id")
 * })
 */
private $address;

地址实体中的国家/地区映射

/**
 * @var \Doctrine\Common\Collections\Collection
 *
 * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Country", inversedBy="address")
 * @ORM\JoinTable(name="address_country",
 *   joinColumns={
 *     @ORM\JoinColumn(name="address_id", referencedColumnName="id")
 *   },
 *   inverseJoinColumns={
 *     @ORM\JoinColumn(name="country_id", referencedColumnName="id")
 *   }
 * )
 */
private $country;

国家实体:

    /**
 * @var string
 *
 * @ORM\Column(name="name", type="string", length=45, nullable=true)
 */
private $name;

/**
 * @var string
 *
 * @ORM\Column(name="isocode2", type="string", length=45, nullable=true)
 */
private $isocode2;

/**
 * @var string
 *
 * @ORM\Column(name="isocode3", type="string", length=45, nullable=true)
 */
private $isocode3;

/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="IDENTITY")
 */
private $id;

/**
 * @var \Doctrine\Common\Collections\Collection
 *
 * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Address", mappedBy="country")
 */
private $address;

/**
 * Constructor
 */
public function __construct()
{
    $this->address = new \Doctrine\Common\Collections\ArrayCollection();
}

如果我尝试这样做

{{ customer.address.country }}

我得到

ContextErrorException: Catchable Fatal Error: Object of class Doctrine\ORM\PersistentCollection could not be converted to string in app/cache/dev/twig/1d/7c/3eec624c629866dcd530ea084487b111c573dbcba579efa7a6b315c46c7a.php line 120

通过 ManyToMany 关联,一个地址可以有多个国家。这符合您的逻辑吗?

如果是,则必须迭代地址的所有国家/地区:

{% for country in customer.address.country %}
    {{ country.isocode2 }}
{% endfor %}

如果您的地址只有一个国家,则必须使用 ManyToOne 关联。然后你可以使用你的语法:

{{ customer.address.country.isocode2 }}