How to use the same entity field in multiple entities?
P粉674999420
P粉674999420 2023-09-11 22:06:11
0
1
397

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粉674999420
P粉674999420

reply all(1)
P粉215292716

You have a few options, you can use traits a> 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
{
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!