Symfony - 为什么不加载两个实体之间关联的实体字段?

Symfony - Why the entity fields from an association between two entities are not loaded?

我有两个实体,MandateProfile

它们之间存在多对多关联。这个协会是这样设置的:

授权

class Mandate
/**
* @ORM\ManyToMany(targetEntity="Profile", inversedBy="mandates", cascade={"persist"})
* @ORM\JoinTable(name="lawyers_mandates")
*/
private $profiles;

简介

class Profile
/**
* @ORM\ManyToMany(targetEntity="Mandate", mappedBy="profiles")
*/
private $mandates;

当saving/editing通过表单授权时,配置文件会很好地保存到数据库中。

问题是当我想加载 Mandate 时,profiles 没有加载对象,尽管所有其他字段已正确加载。

这是我加载 Mandate

的方式
$mandate = $em->getRepository('KrownDashboardBundle:Mandate')->findById($mandateId);
dump($mandate[0]);
dump($mandate[0]->getProfiles());

为什么 配置文件 没有加载?我错过了什么吗?

它被称为 Doctrine 延迟加载又名代理 类。

关系中的 Doctrine 实体在您第一次调用它们之前不会被加载

您需要遍历 Mandate 集合,而不仅仅是 dump()

如果你想让它们加载一个查询,你需要包含带有 leftJoin 的 Mandate 和附加 select('m') 或将 associacion 定义为 EAGER

带有 leftJoin 解决方案的 Querybuilder(我的偏好)

class ProfileRepository extends EntityRepository
{
    public function findAllWithMandates()
    {
        $query = $this->createQueryBuilder('p')
            ->select('p', 'm')
            ->leftJoin('p.mandates', 'm')
            ->getQuery();

        return $query->getResult();
    }
}

急切的解决方案

**
 * @Entity
 */
class CmsGroup
{
    /**
     * @ManyToMany(targetEntity="CmsUser", mappedBy="groups", fetch="EXTRA_LAZY")
     */
    public $users;
}

http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/tutorials/extra-lazy-associations.html