From ebbe670508c650eb5675d6e897dedb0e384692c3 Mon Sep 17 00:00:00 2001 From: Matis MAZINGUE Date: Thu, 13 Jun 2024 09:42:26 +0200 Subject: [PATCH] add like in entity Post --- src/Entity/Post.php | 31 +++++++++++++++++++++++++++++++ src/Entity/User.php | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) diff --git a/src/Entity/Post.php b/src/Entity/Post.php index fa0217a..b8b0046 100644 --- a/src/Entity/Post.php +++ b/src/Entity/Post.php @@ -84,9 +84,16 @@ class Post #[ORM\OneToMany(targetEntity: Comment::class, mappedBy: 'related_post', fetch: 'EXTRA_LAZY')] private Collection $comments; + /** + * @var Collection + */ + #[ORM\ManyToMany(targetEntity: User::class, inversedBy: 'liked_post')] + private Collection $likes; + public function __construct() { $this->comments = new ArrayCollection(); + $this->likes = new ArrayCollection(); } public function getId(): ?int @@ -256,4 +263,28 @@ class Post return $this; } + + /** + * @return Collection + */ + public function getLikes(): Collection + { + return $this->likes; + } + + public function addLike(User $user): static + { + if (!$this->likes->contains($user)) { + $this->likes->add($user); + } + + return $this; + } + + public function removeLike(User $user): static + { + $this->likes->removeElement($user); + + return $this; + } } diff --git a/src/Entity/User.php b/src/Entity/User.php index 8519d9d..81a6b3a 100644 --- a/src/Entity/User.php +++ b/src/Entity/User.php @@ -68,9 +68,16 @@ class User implements UserInterface, PasswordAuthenticatedUserInterface #[ORM\OneToMany(targetEntity: Comment::class, mappedBy: 'author')] private Collection $comments; + /** + * @var Collection + */ + #[ORM\ManyToMany(targetEntity: Post::class, mappedBy: 'likes')] + private Collection $liked_post; + public function __construct() { $this->comments = new ArrayCollection(); + $this->liked_post = new ArrayCollection(); } public function getId(): ?int @@ -189,4 +196,31 @@ class User implements UserInterface, PasswordAuthenticatedUserInterface return $this; } + + /** + * @return Collection + */ + public function getLikedPost(): Collection + { + return $this->liked_post; + } + + public function addLikedPost(Post $likedPost): static + { + if (!$this->liked_post->contains($likedPost)) { + $this->liked_post->add($likedPost); + $likedPost->addLike($this); + } + + return $this; + } + + public function removeLikedPost(Post $likedPost): static + { + if ($this->liked_post->removeElement($likedPost)) { + $likedPost->removeLike($this); + } + + return $this; + } }