skip to Main Content

What is the best way to have the same entity field in many entities?
For example an ‘relatedEntity’ will be appearing in 8 tables.

class User
{
    #[ORMColumn(length: 255)]
        private ?string $relatedEntity = null;
}
class User2
{
    #[ORMColumn(length: 255)]
        private ?string $relatedEntity = null;
}

RelatedEntity in ‘User’ is like a parent field for others. Is it any way to map them between each other to make querying simpler?

I’ve tried OneToOne but everytime it adds a new user and I don’t need to.

3

Answers


  1. Chosen as BEST ANSWER

    I'll try to explain. User have an useruuid field, and other entities got the same useruuid field - just to know which user filled which form.

    Every form got own entity - the rest of app requires that.

    So, how can i join every entity 'uuid' with parent 'user - uuid'?

    It's all about efficiency with query to get all of user filled forms. Now it left joining every entity and check if uuid is matching.


  2. You have a few options, you could use a Trait or use an abstract class. Like @LBA said in his answer, if your entities share many things in common and only have a few differences you may want to look into inheritance mapping.

    Trait example:

    trait RelatedEntityTrait
    {
        #[ORMColumn(length: 255)]
        private ?string $relatedEntity = null;
    
        public function getRelatedEntity(): ?string
        {
            return $this->relatedEntity;
        }
    
        public function setRelatedEntity(?string $relatedEntity): void
        {
            $this->relatedEntity = $relatedEntity;
        }
    }
    
    class User
    {
        use RelatedEntityTrait;
    }
    
    class User2
    {
        use RelatedEntityTrait;
    }
    

    Abstract class example:

    abstract class BaseUser
    {
        #[ORMColumn(length: 255)]
        private ?string $relatedEntity = null;
    
        public function getRelatedEntity(): ?string
        {
            return $this->relatedEntity;
        }
    
        public function setRelatedEntity(?string $relatedEntity): void
        {
            $this->relatedEntity = $relatedEntity;
        }
    }
    
    class User extends BaseUser
    {
    }
    
    class User2 extends BaseUser
    {
    }
    
    Login or Signup to reply.
  3. There is a whole world around this and several approaches.

    • MappedSuperclass
    • Entity Inheritance
    • Single and Class Table Inheritance
      all are supported by Doctrine, read here

    Another option would be to use

    • Traits

    like some common Doctrine Extensions are doing it, please find some approach documented here

    Not knowing exactly what you’re trying to achieve it’s hard to recommend one or other.

    Please come back with more detailed questions.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search