[PR #1535] Fix for many-to-many ignoring "order by" in Criteria #9594

Closed
opened 2026-01-22 16:04:47 +01:00 by admin · 0 comments
Owner

Original Pull Request: https://github.com/doctrine/orm/pull/1535

State: closed
Merged: No


The matching of a Criteria in a many-to-many association will ignore the "order by" clause.

use Doctrine\Common\Collections\Criteria;

/**
 * @Entity @Table(name="hospitals")
 **/
class Hospital
{
    // . . . 

    /**
     * @ManyToMany(targetEntity="User")
     * @JoinTable(name="foo_join_table",
     *      joinColumns={@JoinColumn(name="hospital_id", referencedColumnName="id")},
     *      inverseJoinColumns={@JoinColumn(name="user_id", referencedColumnName="id")}
     *      )
     **/
    protected $users;

    public function getUsers()
    {
        $criteria = Criteria::create()
            // . . .
            ->orderBy(array("name" => Criteria::ASC));

        return $this->users->matching($criteria);
    }
}

// . . .

$users = $entityManager->find(Hospital::class, $hospital_id)->getUsers();

// $users will not be sorted by "name"

This is a very crude fix. I just stated using doctrine this week so I'm sure there's a better/more secure way to fix it. But this hot fix got it working on my local installation. :)

**Original Pull Request:** https://github.com/doctrine/orm/pull/1535 **State:** closed **Merged:** No --- The matching of a `Criteria` in a many-to-many association will ignore the "order by" clause. ``` php use Doctrine\Common\Collections\Criteria; /** * @Entity @Table(name="hospitals") **/ class Hospital { // . . . /** * @ManyToMany(targetEntity="User") * @JoinTable(name="foo_join_table", * joinColumns={@JoinColumn(name="hospital_id", referencedColumnName="id")}, * inverseJoinColumns={@JoinColumn(name="user_id", referencedColumnName="id")} * ) **/ protected $users; public function getUsers() { $criteria = Criteria::create() // . . . ->orderBy(array("name" => Criteria::ASC)); return $this->users->matching($criteria); } } // . . . $users = $entityManager->find(Hospital::class, $hospital_id)->getUsers(); // $users will not be sorted by "name" ``` This is a very crude fix. I just stated using doctrine this week so I'm sure there's a better/more secure way to fix it. But this hot fix got it working on my local installation. :)
admin added the pull-request label 2026-01-22 16:04:47 +01:00
admin closed this issue 2026-01-22 16:04:48 +01:00
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: doctrine/archived-orm#9594