php - Symfony 4/Doctrine 2 - 获取真实对象而不是代理

标签 php symfony doctrine-orm symfony4 many-to-one

我有以下实体:

/**
 * @ORM\Entity(repositoryClass="App\Repository\CourseLevelRepository")
 */
class CourseLevel
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @var CourseLevel
     *
     * @ORM\ManyToOne(targetEntity="App\Entity\CourseLevel", fetch="EAGER")
     * @ORM\JoinColumn(nullable=true, referencedColumnName="id")
     */
    private $nextCourseLevel;   


    ...
}

如您所见,它构建了一个树结构,因此任何记录都可以通过 $nextCourseLevel 的 ManyToOne 关系指向它的父级。

然后我使用存储库中的查询获取元素列表:

class CourseLevelRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, CourseLevel::class);
    }

    public function fetchFiltered(array $filters)
    {
        $builder = $this->createQueryBuilder('cl');
        $builder->setFirstResult(0);
        $builder->setMaxResults(10)
        $builder->orderBy('cl.name', 'asc');

        return $builder->getQuery()->getResult();
    }
}

让我们假设以下数据集:

id | next_course_level
-------------------------
1  | 2
2  | null

为此,我将收到以下对象: - id = 1 的对象,它是 App\Entity\CourseLevel 的对象($nextCourseLevel 设置为对象 id = 2,这是一个代理) - id = 2 的对象,它是一个代理对象。

发生这种情况可能是因为关系 - id=1 的对象指向 id=2 作为父对象。

但是我怎样才能强制获取所有数据作为真实对象,而不是代理?放 fetch="EAGER"不会改变任何东西:(

最佳答案

您必须加入并选择您的协会才能获得对象而不是代理。

查看文档 here .

来自文档的示例:

// src/Repository/ProductRepository.php
public function findOneByIdJoinedToCategory($productId)
{
$entityManager = $this->getEntityManager();

$query = $entityManager->createQuery(
    'SELECT p, c
    FROM App\Entity\Product p
    INNER JOIN p.category c
    WHERE p.id = :id'
)->setParameter('id', $productId);

return $query->getOneOrNullResult();
}

“当您一次检索所有产品和类别数据(通过连接)时,Doctrine 将返回真正的类别对象,因为不需要延迟加载任何内容。”

关于php - Symfony 4/Doctrine 2 - 获取真实对象而不是代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59281663/

相关文章:

php - 如何从返回 3 维数组的查询中获取数据并在 symfony 3 中的 Twig View 上设置值

doctrine - removeElement() 和clear() 在具有数组集合属性的 Doctrine 2 中不起作用

php - DBAL 基数违规错误

php - Google 图表从一行中获取数据

php - 如何根据 "enum"列获取分类的 laravel Eloquent 结果并将其显示在一页中?

php - += 是做什么用的?

php - 为什么我的临时文件不可写入/tmp 文件夹 - linux 服务器(centos)

symfony - 如何从 symfony2 项目中删除供应商?

php - 如何在 doctrine2 中找到实体

doctrine-orm - 如何使用 Doctrine 更改列字符集和排序规则?