Home > OS >  Symfony : how to construct the good relation between my entities?
Symfony : how to construct the good relation between my entities?

Time:11-04

I'm a new user of Symfony, and I want to make a relation between 2 entities.

I have an entity named 'Suggest' and the other one 'Car'

Each suggest can have one or many cars, and a car can be used to 0 or multiple suggest

I want a new field named 'Cars' ( field for the name of cars) in my 'Suggest' entity, but I don't want new field in 'Car' entity

How can I do it ?

I tried to make a relation ManyToOne on my Suggest entity but it create me an id field of cars, and I can only put one.

with a ManyToMany relation, it is possible to get only a new field on my 'suggest' entity ?

CodePudding user response:

Assuming you're using the make:entity command: if you add a cars property to your Suggest entity, and make it a ManyToMany relation to Car, it does not add an extra property to the Car class (you can say no to that):

Car:

<?php

namespace App\Entity;

use App\Repository\CarRepository;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass=CarRepository::class)
 */
class Car
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    public function getId(): ?int
    {
        return $this->id;
    }
}

And Suggest:

<?php

namespace App\Entity;

use App\Repository\SuggestRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass=SuggestRepository::class)
 */
class Suggest
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\ManyToMany(targetEntity=Car::class)
     */
    private $cars;

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

    public function getId(): ?int
    {
        return $this->id;
    }

    /**
     * @return Collection<int, Car>
     */
    public function getCars(): Collection
    {
        return $this->cars;
    }

    public function addCar(Car $car): self
    {
        if (!$this->cars->contains($car)) {
            $this->cars[] = $car;
        }

        return $this;
    }

    public function removeCar(Car $car): self
    {
        $this->cars->removeElement($car);

        return $this;
    }
}
  • Related