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
206 views
in Technique[技术] by (71.8m points)

php - Doctrine ManyToOne relationship - auto-remove on "set"

I'm working with relationships in Doctrine (using Symfony 5). What I have is these 2 relations:

  1. User
  2. Availability

User has an ID and has Many Availabilities.

So Entity User has

/**
 * @ORMOneToMany(targetEntity="UserAvailability", mappedBy="user")
 */
private $availability;

and the reverse on Entity Availability.

Availability is a relation with:

id, user_id, day_name, start_time and end_time, that simple.

What I already achieved with ManyToMany and I want to achieve in this case too is:

I need to receive the entire set of availabilities for a User from the client and use it to update the availabilities of my User, so I defined a setAvailability method which receives a Collection of Availability entities and simply does

$this->availabilities = $availabilities.

This works when I add new availabilities but the ones that are on the DB and not in the collection are not dropped when I persist the entity.

The same method works flawlessly with ManyToMany Relationship.

What am I missing?

*** UPDATE **

public function setAvailability($availability): self
    {
        $this->availability = $availability;
        return $this;
    }

this same code works when removing relations in ManyToMany relationship but not in ManyToOne, the attribute "availability" is correctly set, but when using persist/flush the availability which was removed is not removed on the DB.

Thanks


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

1 Answer

0 votes
by (71.8m points)

Try to set the attributes as in the example from the doctrine documentation below :

<?php
use DoctrineCommonCollectionsArrayCollection;

/** @Entity */
class User
{
    // ...
    /**
     * One user has many availabilities. This is the inverse side.
     * @OneToMany(targetEntity="Availability", mappedBy="user")
     */
    private $availabilities;
    // ...

    public function __construct() {
        $this->availabilities = new ArrayCollection();
    }
}

/** @Entity */
class Availability
{
    // ...
    /**
     * Many availabilities have one user. This is the owning side.
     * @ManyToOne(targetEntity="User", inversedBy="availabilities")
     * @JoinColumn(name="user_id", referencedColumnName="id")
     */
    private $user;
    // ...
}

the attribute mappedBy and inversedBy are necessary for relations


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

...