Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
697 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()?

See Question&Answers more detail:os

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...