wawa
wawa

Reputation: 5066

Symfony Entity - Order joined Entities in a ManyToMany join

So let's say we use a User and a Ticket class. They are normal entities, nothing fancy.

The User class contains this lines:

/**
 * @ORM\ManyToMany(targetEntity="Ticket", mappedBy="collaborateurs")
 **/
private $tickets;

The Ticket class contains this:

/**
 * @ORM\ManyToMany(targetEntity="User", inversedBy="tickets")
 * @ORM\JoinTable(name="users_to_tickets")
 **/
private $collaborateurs;

To get all ticket's a user has I can just call the getTickets() function created by Symfony. As far as good. The Ticket class has a few additional fields like updated which is a DateTime field or status which is an integer. I would like to sort those tickets by status DESC and updated DESC

I know I could just make a function in the repository like findTicketsByUserOrderedByFooBar($user), but I'm wondering if there isn't a better way.

Upvotes: 2

Views: 895

Answers (3)

Matteo
Matteo

Reputation: 39380

You can add an Helper method to your User entity and sort/filter DIRECTLY on the ArrayCollection with doctrine2 criteria. Something like this:

/**
* this return a ArrayCollection
*/
public function getTicketsByUserOrderedByFooBar()
{
            $criteria = Criteria::create()
                        ->orderBy(array('foo'=>'DESC','bar' =>'ASC'))

        return $this->tickets->matching($criteria);

}


/**
* this return a ArrayCollection
*/
public function getTicketsByUserOrderedBytitle()
{
            $criteria = Criteria::create()
                        ->orderBy(array('title'=>'DESC'))

        return $this->tickets->matching($criteria);

}

See also this

Hope this help.

Upvotes: 1

qooplmao
qooplmao

Reputation: 17759

If you always want your tickets to be in that order you can set and orderBy on the association.

/**
 * @ORM\ManyToMany(targetEntity="Ticket", mappedBy="collaborateurs")
 * @ORM\OrderBy({"status" = "DESC", "updated" = "DESC"})
 **/
private $tickets;

Upvotes: 7

Ewan Valentine
Ewan Valentine

Reputation: 3931

Creating a function the way you suggested would be the suggested approach.

Upvotes: 0

Related Questions