search

Home  >  Q&A  >  body text

How to use the same entity field in multiple entities?

What is the best way to have the same entity fields in many entities? For example, "Related Entities" will appear in 8 tables.

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

RelatedEntity in "User" is like a parent field for others. Is there any way to map them to each other to make querying simpler?

I tried OneToOne but every time it adds new users but I don't need to do that.

P粉674999420P粉674999420470 days ago480

reply all(1)I'll reply

  • P粉215292716

    P粉2152927162023-09-12 17:26:55

    You have a few options, you can use traits or use abstract classes. Like @LBA said in his answer, if your entities have a lot in common and only a few differences, you might want to look into inheritance mapping.

    Feature example:

    trait RelatedEntityTrait
    {
        #[ORM\Column(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
    {
        #[ORM\Column(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
    {
    }
    

    reply
    0
  • Cancelreply