I have been checking the documentation and got confused, can someone advise me how to add one-to-many relationships for existing tables? Adequately userid is supposed to refer to the user id.
Entity for a user that may have multiple doors
#[ORMEntity(repositoryClass: UserRepository::class)]
#[ORMTable(name: '`user`')]
#[UniqueEntity(fields: ['username'], message: '321')]
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
#[ORMId]
#[ORMGeneratedValue]
#[ORMColumn]
private ?int $id = null;
public function getId(): ?int
{
return $this->id;
}
}
Entity for the doors
#[ORMTable(name: '`doors`')]
#[UniqueEntity(fields: ['serialNumber'], message: '312132')]
#[ORMEntity(repositoryClass: DoorsRepository::class)]
class Doors
{
#[ORMId]
#[ORMGeneratedValue]
#[ORMColumn]
private ?int $id = null;
#[ORMColumn]
private ?int $userid = null;
private ?string $purchaseFilename = null;
public function getId(): ?int
{
return $this->id;
}
public function setId(int $id): static
{
$this->id = $id;
return $this;
}
public function getUserid(): ?int
{
return $this->userid;
}
}
2
Answers
as your properties already exist, you have to update their annotations like based on Symfony Associations Doc and the type used.
Then you will have to run make a new migration and run it using:
In addition, you may take a look at How to embed a collection of form to handle your forms.
If it’s was helpull, make sure to accept the answer !
You have an easy way to add relations in Symfony.
You can use the command
php bin/console make:entity
.Then call your entity (in your example
Doors
), add a fielduser
, declare typeOneToMany
(or see more relation types with therelation
key), related the entity toUser
, and voila.Then
php bin/console make:migration
: it will write the change inmigrations
folder ; you’ll see it automatically add a fielduser_id
in Door table, related to youruser.id
(as id is the identifier of your User entity).And
php bin/console doctrine:migrations:migrate
: queries will be executed in your db.I hope it will help