0
Follow
2
View

ManyToMany Relationship With Type Symfony Doctrine

dai_feng0118 注册会员
2023-01-25 12:00

Normaly, you cannot do that on database, because it not safe. Why is it not safe? because you can have an id in the user column of userGroup table that refer to nothing as it is not linked.

I will write what you should have done, and how you can achieve what you want using your own method:

In your UserGroup entities, have 2 columns (admin and client) which are linked to the related entities. They can be null (Client is null and admin contain the id of admin entity if it is an admin and vice versa). Then you can delete the type column

As it cannot be done in the database, you will have to do it in some manager. Have a method getUser which will check on your type attribute and return the associated entity from the current id stored in $user

example:

    public function getUserFromGroupUser(GroupUser $groupUser){
        if('Entity\Admin' ===$groupUser->getType()){
            return $this->adminRepository->find($groupUser->getUser());
        }
        if('Entity\Client' ===$groupUser->getType()){
            return $this->ClientRepository->find($groupUser->getUser());
        }
        throw new \RuntimeException('the type does not exist');
    }

About the Author

Question Info

Publish Time
2023-01-25 12:00
Update Time
2023-01-25 12:00