Faery
Faery

Reputation: 4650

Sorting information from related tables - Symfony2

A. I have a table with users and a table with friends and here are their connections:

This in the User class:

    /**
     * @ORM\OneToMany(targetEntity="Friend", mappedBy="user")
     */
    protected $friends;

public function __construct()
    {
        $this->friends = new ArrayCollection();
    }

and this is in the Friend class:

/**
 * @ORM\ManyToOne(targetEntity="User", inversedBy="friends")
 * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
 */
protected $user;

I have an template, in which I render the friends of the current user just using

$friends = $user->getFriends(); 

But now I want to be able to sort the friends of the user. I created a repository class with this function:

public function findAllOrderedByName()
    {
        return $this->getEntityManager()
            ->createQuery('SELECT f FROM EMMyFriendsBundle:Friend f ORDER BY f.name ASC')
            ->getResult();
    }

but it displays all the friends of all the users, not just the current user. Is there a way to show only the friends of the current user without using something like "WHERE friend.user_id = user.id"? If yes, please tell me how to do it.

B. Another thing I would like to ask is how to manage my controllers.

This is the action which renders the template to show all unsorted friends:

/*
 * @Displays the basic information about all the friends of an user
 */
public function displayAction()
{
    $user = $this->get('security.context')->getToken()->getUser();

    if($user->getName() === NULL)
    { 
        $name = $user->getUsername();
    } 
    else 
    {    
        $name = $user->getName();
    }

    $this->get('session')->setFlash('hello', 'Hello, '.$name.'!');

    $friends = $user->getFriends();

    $cat = new Category();

    $dd_form = $this->createForm(new \EM\MyFriendsBundle\Entity\ChooseCatType(), $cat);

    return $this->render('EMMyFriendsBundle:Home:home.html.twig', array(
        'name' => $name, 'friends' => $friends, 'user' => $user,
        'dd_form' => $dd_form->createView()));
}

And I have a sortAction, but I don't know how to write it. It should be the same as the above, only the row

 $friends = $user->getFriends();

should be replaced with

$friends = $em->getRepository('EMMyFriendsBundle:Friend')
        ->findAllOrderedByName();

but if I copy it, it's a lot code duplication and it's stupid. I thought of one controller with an if-statement, but what to have in it? Please give me some ideas! Thanks in advance!

Upvotes: 0

Views: 123

Answers (1)

Carlos Granados
Carlos Granados

Reputation: 11351

Do this:

/**
 * @ORM\OneToMany(targetEntity="Friend", mappedBy="user")
 * @ORM\OrderBy({"name" = "ASC"})
 */
protected $friends;

Upvotes: 2

Related Questions