简体   繁体   中英

Doctrine, Symfony3, Query entities from other entity array

I have a problem using Doctrine with my entities. See below for the question.
My entities:

class User
{
    // ...

    /**
     * @var ArrayCollection
     *
     * @ORM\OneToMany(targetEntity="Friend", mappedBy="userB")
     */
    private $friends;

    // ...

    /**
     * Get friends
     *
     * @return ArrayCollection
     */
    public function getFriends()
    {
        return $this->friends;
    }
}

And

class Friend
{
    /**
     * @var string
     *
     * @ORM\Column(name="relation", type="string", length=255)
     */
    private $relation;

    /**
     * @var int
     *
     * @ORM\ManyToOne(targetEntity="User", inversedBy="friendsWithMe")
     */
    private $userA;

    /**
     * @var int
     *
     * @ORM\ManyToOne(targetEntity="User", inversedBy="friends")
     */
    private $userB;
}

And my UserController has this:

/**
 * Show the user's friendzone
 *
 * @Route("/friendzone", name="show_friends")
 */
public function showFriendzoneAction()
{

    $friends = $this->getUser()->getFriends();
    $users = ???

    return $this->render('DevLeaguesBundle:User:show_reduced.html.twig', array(
        'users' => $friends,
    ));
}

What I would like my controller to do is to define $users as an array of Users fetched from $friends . The solution might be very simple.

for array you need to build dql-query in UserRepository and get result as array OR you can use relation getFriends and get array collection from your user entity. But, i don't understand why you don't use manytomany relation, in which case friends will be User entities, not Friend entities.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM