【问题标题】:Symfony 4 - Can't access to my entity collectionSymfony 4 - 无法访问我的实体集合
【发布时间】:2019-09-05 13:39:34
【问题描述】:

我有一个带有 User 实体和 SoldeConges 实体的 Symfony 4 项目。 一个用户有一个 SoldeConges 集合。

但是当我转储 $user->getSoldeConges() 时,集合是空的。

我的用户实体:

/**
 * @ORM\OneToMany(targetEntity="App\Entity\SoldeConges", mappedBy="user", orphanRemoval=true)
 */
private $soldeConges;

/**
     * @return Collection|SoldeConges[]
     */
    public function getSoldeConges(): Collection
    {
        return $this->soldeConges;
    }

我的用户有 3 个soldeConges:

PhpMyAdmin SoldeConge 表:

当我在控制器中为我的用户(即用户号 1)进行转储时:

$soldeConges = $this->getUser()->getSoldeConges();
        dump($soldeConges);

我已经:

那么,为什么不能访问我的用户 SoldeConges 收藏?

【问题讨论】:

    标签: symfony collections doctrine


    【解决方案1】:

    1) 获取您的 soldeConges(这是 symfony 3 代码,将其调整为 4 ;-)):

    $em = $this->getDoctrine()->getManager();
    $soldeCongesRepository= $em->getRepository('AppSoldeConges:SoldeConges');
    $soldeConges = $soldeCongeRepository->findBy(['userId'=>$this->getUser()->getId()]);
    

    2) 这可能是由于 Doctrine 延迟加载造成的。 试试 fetch="EAGER"(默认是 LAZY):

     * @ORM\OneToMany(targetEntity="App\Entity\SoldeConges", mappedBy="user", orphanRemoval=true, fetch="EAGER")
    

    【讨论】:

    • 您好! fetch="EAGER" 效果很好!你能给我解释一下这是什么吗?没有风险?
    【解决方案2】:

    如果您尝试访问,Doctrine 会在一次加载整个集合。转储是您放置转储()语句时的内存模型。

    如果您应该首先渲染集合(或者即使您只在集合上使用 count() 方法)然后使用 dump() 语句,您将看到您的集合已加载。这就是所谓的延迟加载系统。它会在需要时执行第二个查询。但是您可能知道如果两个查询可以得到一个查询,那么它应该会更好更快。 另一方面,如果您有拥有大量集合的实体,这可能会导致严重的问题。在这种情况下,您可以使用“额外延迟加载”。 (参见文档)

    无论如何,如果您想让您的集合立即与您的实体一起加载,那么您可以使用您自己的具有一个或多个 JOINS 的 DQL 查询。下面是您的存储库示例,其中包含一个名为 findAllWithJoin 的新函数。从您的控制器而不是 findAll() 调用该函数。

    namespace App\Repository;
    
    use App\Entity\User;
    use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
    use Doctrine\Common\Persistence\ManagerRegistry;
    
    class UserRepository extends ServiceEntityRepository
    {
        public function __construct(ManagerRegistry $registry)
        {
            parent::__construct($registry, User::class);
        }
    
        public function findAllWithJoin()
        {
            $entityManager = $this->getEntityManager();
    
            $query = $entityManager->createQuery('SELECT u, sc FROM User u JOIN u.soldeConges sc');
    
            return $query->execute();
        }
    }
    

    【讨论】:

    • 您好!感谢您的回答 !我刚刚将 fetch="EAGER" 添加到我的soldeConges 中,它可以工作。谢谢你 ! :D
    猜你喜欢
    • 2019-05-02
    • 2018-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-06
    • 1970-01-01
    • 2016-07-20
    • 1970-01-01
    相关资源
    最近更新 更多