I need to set follower, following (myFriends) hasFriend logic to my project. column "odobera" means "following" to example nick(id user) odobera (following to this user). User (25) is following user(37).
Requests table:

User entity:
/**
* @ORM\OneToMany(targetEntity="TB\RequestsBundle\Entity\Requests", mappedBy="odobera")
*/
protected $followers;
/**
* @ORM\OneToMany(targetEntity="TB\RequestsBundle\Entity\Requests", mappedBy="nick")
*/
protected $myFriends;
public function __construct()
{
parent::__construct();
$this->followers = new \Doctrine\Common\Collections\ArrayCollection();
$this->myFriends = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get myFriends
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getMyFriends()
{
return $this->myFriends;
}
/**
*
* @param \TB\UserBundle\Entity\User $user
* @return bool
*/
public function hasFriend(User $user)
{
return $this->myFriends->contains($user);
}
class Requests
{
/**
* @ORM\ManyToOne(targetEntity="TB\UserBundle\Entity\User", inversedBy="myFriends")
* @ORM\JoinColumn(name="nick", referencedColumnName="id")
*/
protected $nick;
/**
* @ORM\ManyToOne(targetEntity="TB\UserBundle\Entity\User",inversedBy="followers")
* @ORM\JoinColumn(name="odobera", referencedColumnName="id")
*/
protected $odobera;
In controller:
$myFollowers=$user->getMyFriends();
returns:

What is good: returns 1 record. I actually follow just one person as you can see here the id of record is 24395
DB requests table:

I don't know if is good that getMyFriends function returns response in that "format". Please look at it carefully.
Then I have select followers from query and in loop:
{% for follower in followers %}
and i print data like this (works greate) {{ follower.nick }}
or if i want some fields from user entity {{ follower.nick.rank }}
{% endfor %}
But the problem is here:
{% if (app.user.hasFriend(follower.nick)) %}
That returns false, why? I follow this user as I checked in controller with dump :P Few lines over.
The problem seems to be that you are comparing two different type variable.
When you do this: {% if (app.user.hasFriend(follower.nick)) %}
the following function is called:
/**
*
* @param \TB\UserBundle\Entity\User $user
* @return bool
*/
public function hasFriend(User $user)
{
return $this->myFriends->contains($user);
}
This function is called, taking a User
type $user
variable and you then use the contains()
function on $this->myFriends
.$this->myFriends
is an ArrayCollection
of Requests
(so different type than User
) and from the doctrine documentation about contains()
:
The comparison of two elements is strict, that means not only the value but also the type must match.
来源:https://stackoverflow.com/questions/15074830/symfony-doctrine-entity-friend-hasfriend-followers