Search code examples
symfonymany-to-many

Add extra fields in ManyToMany relationship Symfony 6


Hi so i created a many to many relationship between 2 entities named client and offre

here is my entity client :

#[ORM\ManyToMany(targetEntity: Offre::class, inversedBy: 'clients')]
#[ORM\JoinColumn(name:"CLIENTID", referencedColumnName:"clientid")]
#[ORM\InverseJoinColumn(name: "OFFREID", referencedColumnName: "offreid")]
#[ORM\JoinTable(name: "clients_offre")] 
private Collection $offres;

here is my entity offre

#[ORM\ManyToMany(targetEntity: client::class, mappedBy: 'offres')]
private Collection $clients;

As planned it created me a table named clients_offre with CLIENTID and OFFREID.

Now i want to add a commentaire field in this table but this field has no referencedColumnName so i don't know how to do it.

Thanks in advance to those who take the time to help!


Solution

  • You cannot create a direct relationship between two entities with extra columns.

    You need to create a new Entity that will be the intermediary between Client and Offre.

    Your new entity could be called ClientOffre and will be related to both Client and Offre with two OneToMany and two ManyToOne.

    public class ClientOffre {
        #[ORM\ManyToOne(targetEntity: Client::class)]
        #[ORM\JoinColumn(name:"client_id", referencedColumnName:"id")]
        private $client;
    
        #[ORM\ManyToOne(targetEntity: Offre::class)]
        #[ORM\JoinColumn(name:"offre_id", referencedColumnName:"id")]
        private $offre;
    
        #[ORM\Column(type: Types::TEXT, nullable: true)]
        private ?string $comment = null;
    }
    

    And your current entity will have a OneToMany relationship with this new entity:

    public class Client {
        #[ORM\OneToMany(targetEntity: ClientOffre::class, mappedBy: "client")]
        private Collection $clientOffres;
    }
    
    public class Offre {
        #[ORM\OneToMany(targetEntity: ClientOffre::class, mappedBy: "offre")]
        private Collection $clientOffres;
    }