K
K
KerryDarko2016-02-19 13:15:26
symfony
KerryDarko, 2016-02-19 13:15:26

Doctrine: Is it possible to do sorting on a collection in an entity?

I have a Company entity and an associated Album (1:m) entity. That is, there is a company and it has a collection of photo albums.
Let's say I also have a bunch of just left photos and I want to make a default album out of them when displayed on the page. I create this album with my hands, add these photos to it, add the album to the collection in the company. Everything is great, but this album, of course, at the end. I want him to be first. Is there any way to do sorting?
So far, the only solution is to select all albums from the collection into a variable, remove them from the collection, add the default album to the collection, add all the rest.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis, 2016-02-19
@KerryDarko

$criteria = new \Doctrine\Common\Collections\Criteria(null, ['id' => 'DESC']);
$collection = new \Doctrine\Common\Collections\ArrayCollection([
    ['id' => '10'],
    ['id' => '100'],
]);
$collection2 = $collection->matching($criteria);

echo "<pre>";
var_dump($collection->toArray());
var_dump($collection2->toArray());
echo "</pre>";
exit("File: " . __FILE__ . " Line: " . __LINE__);

// array(2) {
//   [0]=>
//   array(1) {
//     ["id"]=>
//     string(2) "10"
//   }
//   [1]=>
//   array(1) {
//     ["id"]=>
//     string(3) "100"
//   }
// }
// array(2) {
//   [1]=>
//   array(1) {
//     ["id"]=>
//     string(3) "100"
//   }
//   [0]=>
//   array(1) {
//     ["id"]=>
//     string(2) "10"
//   }
// }

B
BoShurik, 2016-02-19
@BoShurik

doctrine-orm.readthedocs.org/projects/doctrine-orm...
If you don't need to save albums, then just like you said:

$collection->setAlbums(
    new ArrayCollection(
        array_merge(
            array($album), 
            $collection->getAlbums()->toArray()
        )
    )
);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question