Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 248
Iter Ator Avatar asked Sep 15 '19 23:09

Iter Ator


1 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

like image 96
nemanja cucurevic Avatar answered Nov 18 '22 16:11

nemanja cucurevic