如何在 Symfony 4 中制作相似和不同的东西?

How to make like and unlike in Symfony 4?

我在我的项目中设计类似的功能,但我无法显示图标。

User.php

/**
 * @ORM\ManyToMany(targetEntity="App\Entity\Image", inversedBy="users")
 */
private $likes;

public function __construct()
{
    $this->images = new ArrayCollection();
    $this->likes = new ArrayCollection();
}
 ....
 /**
 * @return Collection|Image[]
 */
public function getLikes(): Collection
{
    return $this->likes;
}

public function addLike(Image $like): self
{
    if (!$this->likes->contains($like)) {
        $this->likes[] = $like;
    }

    return $this;
}

public function removeLike(Image $like): self
{
    if ($this->likes->contains($like)) {
        $this->likes->removeElement($like);
    }

    return $this;
}

Image.php

/**
 * @ORM\ManyToMany(targetEntity="App\Entity\User", mappedBy="likes")
 */
private $users;

public function __construct()
{
    $this->likes = new ArrayCollection();
    $this->users = new ArrayCollection();
}
...
/**
 * @return Collection|User[]
 */
public function getUsers(): Collection
{
    return $this->users;
}

public function addUser(User $user): self
{
    if (!$this->users->contains($user)) {
        $this->users[] = $user;
        $user->addLike($this);
    }

    return $this;
}

public function removeUser(User $user): self
{
    if ($this->users->contains($user)) {
        $this->users->removeElement($user);
        $user->removeLike($this);
    }

    return $this;
}

树枝

          <a href="{{ path('like',{'id':image.id}) }}">
            {% if  user likes the image display this %}  
              <i id="like" class="{{ unlike }} text-danger"></i>&nbsp;{{ image.users.count  }} 

              {% else show this %}
                     <i id="like" class="{{ like }} text-danger"></i>&nbsp;{{ image.users.count  }} 
              {% endif %}
              </a>

用户资料库

public function findByLikes($value): ?User
{
    return $this->createQueryBuilder('l')
        ->leftJoin('l.likes', 'u')
        ->leftJoin('u.user','e')
        ->addSelect('u','e')
        ->where('l.id = :val')
        ->setParameter('val', $value)
        ->getQuery()
        ->getOneOrNullResult()
    ;
}

谁能帮我写代码?我认为控制器没有问题。可能是我无法在树枝中编写逻辑。 所以我的意图是为喜欢和不喜欢的人显示图标。我对喜欢和不喜欢都使用了单个图标。如果用户点击喜欢的图标应该翻转到不喜欢的图标,反之亦然。

假设用户已连接,您可以通过这种方式显示正确的图标:

      <a href="{{ path('like',{'id':image.id}) }}">
      {% if image.users.contains(app.user) %}
          <i id="like" class="{{ unlike }} text-danger"></i>&nbsp;{{ image.users.count }} 
      {% else %}
          <i id="like" class="{{ like }} text-danger"></i>&nbsp;{{ image.users.count }} 
      {% endif %}
       </a>