仅从实体关系中获取 ID 而无需在 Doctrine 中获取整个对象 [英] Getting only ID from entity relations without fetching whole object in Doctrine

查看:26
本文介绍了仅从实体关系中获取 ID 而无需在 Doctrine 中获取整个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个实体,它引用自身来映射父子关系

Assume I've an entity, which references itself to map parent-child-relations

class Food
{
    /**
     * @ORMId
     * @ORMColumn(type="integer")
     * @ORMGeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORMManyToOne(targetEntity="Food", inversedBy="foodChildren")
     * @ORMJoinColumn(name="food_group_id", nullable=true)
     */
    protected $foodGroup;

    /**
     * @ORMOneToMany(targetEntity="Food", mappedBy="foodGroup", fetch="LAZY", cascade={"remove"})
     */
    protected $foodChildren;

我有一个用例,我想获取实体的 food_group_id 而不从数据库中获取完整的父对象.使用 fetch="LAZY" 不会阻止 Doctrine 再次查询.有没有办法在获取 $food->getFoodGroup() 时只返回 ID?

I have a use case where I want to get food_group_id of an entity without getting full parent object from database. Using fetch="LAZY" doesn't keep Doctrine from querying again. Is there a way to return only the ID when getting $food->getFoodGroup()?

推荐答案

不要让生活复杂化,你可以自己做

Don't complicate your life, you can just do

$food->getFoodGroup()->getId()

不会执行任何额外的查询或触发延迟加载!

This WILL NOT perform any additional query or trigger lazy load!

为什么?因为你的 $food->foodGroup 是一个知道它的 ID 的代理对象.如果您调用某个尚未加载的字段的 getter 方法,它只会进行延迟加载.

Why? Because your $food->foodGroup is a proxy object which knows about it's ID. It will only do lazy load if you call a getter method of some field which hasn't been loaded.

这篇关于仅从实体关系中获取 ID 而无需在 Doctrine 中获取整个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆