Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
858 views
in Technique[技术] by (71.8m points)

symfony - Getting only ID from entity relations without fetching whole object in 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;

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()?

question from:https://stackoverflow.com/questions/19139970/getting-only-id-from-entity-relations-without-fetching-whole-object-in-doctrine

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Don't complicate your life, you can just do

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

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...