Home » Php » php – How is it possible to completely refresh an Entity with a @OneToMany relationship?

php – How is it possible to completely refresh an Entity with a @OneToMany relationship?

Posted by: admin July 12, 2020 Leave a comment

Questions:

In my project there is a Cart and a CartItem entity, like this:

class Cart {

    /**
     * @OneToMany(targetEntity="CartItem", mappedBy="cart")
     */
    private $items;

    // ...
}

class CartItem {

    /**
     * @ManyToOne(targetEntity="Cart", inversedBy="items")
     * @JoinColumn(name="cart_id", referencedColumnName="cart_id")
     */
    private $cart;

    // ...
}

If I call EntityManager::refresh($cart), then the items in it are not updated, only the Cart object.

How is it possible to refresh an object and all of its contents from the database, without explicitly call refresh on each of the sub elements?

I would like to avoid calling EntityManager::clear(), because it would cause bugs in other parts of the program.

How to&Answers:

You can do it like this:

class Cart {

    /**
     * @OneToMany(targetEntity="CartItem", mappedBy="cart", cascade={"refresh"})
     */
    private $items;

    // ...
}

Use “cascade” with caution as stated in the documentation:
https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/best-practices.html#use-cascades-judiciously