I have a flexible database structure, where i can assign any tag to any post and have a custom label-value for it
I have a perfectly working SQL query for it, but now i want to migrate it to Doctrine ORM and classic solution (as far as i've found) for that kind of design is:
class Post
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private int $id;
#[ORM\Column(length: 100)]
private string $name;
#[ORM\OneToMany(mappedBy: "post", targetEntity: PostTag::class)]
private Collection $tags;
}
class PostTag
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private int $id;
#[ORM\ManyToOne(targetEntity: Post::class)]
#[ORM\JoinColumn(nullable: false)]
private Post $post;
#[ORM\ManyToOne(targetEntity: Tag::class)]
#[ORM\JoinColumn(nullable: false)]
private Tag $tag;
}
class Tag
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private int $id;
#[ORM\Column(length: 100)]
private string $name;
#[ORM\OneToMany(mappedBy: "tag", targetEntity: PostTag::class)]
private Collection $posts;
}
But problem is, later if you want to fetch post with all its attributes your code will look something like that:
$repository = $em->getRepository(Post::class);
$post = $repository->find(1); // fetch first Post from database
$postTag = $post->getPostTags()->first(); // get first tag from all post tags
$name = $postTag->getTag()->getName(); // post tag -> get tag, tautology at its best
$value = $postTag->getValue(); // but value is in post tags list
And this solution works, but it's pretty ugly if you want to have tags key => value list, since in Post you first need to retrieve all PostTags and from each of them you retrieve Tag name one by one.
Image how much better would it look like this:
$repository = $em->getRepository(Post::class);
$post = $repository->find(1);
$tag = $post->getTags()->first();
$name = $tag->getName();
$value = $tag->getValue();
But the only way i've achieved that is with many-to-many connection between Post and Tag, but then i don't have a value (of course, because Tag don't have that column), is there a solution to have a more clean entities code ?
