简体   繁体   English

使用 Doctrine ODM 订购嵌入式文档

[英]Ordering embedded documents with Doctrine ODM

I'm trying to order my embed documents.我正在尝试订购我的嵌入文档。

The field looks like this该字段看起来像这样

/**
 * @ODM\EmbedMany(targetDocument=Image::class, strategy="set")
 * @ODM\Index(keys={"order"="asc"})
 * @Groups({"offer:read"})
 */
protected $images = [];

The Image EmbeddedDocument图像嵌入文档

namespace App\Document\Embedded;

use App\Document\Traits\NameableTrait;
use App\Document\Traits\OrderableTrait;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;

/**
 * @ODM\EmbeddedDocument
 */
class Image
{
    use NameableTrait;
    use OrderableTrait;
    …
}

And the orderable trait和可排序的特征

namespace App\Document\Traits;

use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Symfony\Component\Serializer\Annotation\Groups;

trait OrderableTrait
{
    /**
     * @ODM\Field(type="int")
     * @Groups({"offer:read"})
     *
     * @var int|null
     */
    private $order;

    public function getOrder(): int
    {
        return $this->order;
    }

    public function setOrder(int $order): void
    {
        $this->order = $order;
    }
}

I updated the indexes with bin/console doctrine:mongodb:schema:update我用bin/console doctrine:mongodb:schema:update更新了索引bin/console doctrine:mongodb:schema:update

However my Images are not ordered.但是我的图像没有被订购。 Are the indexes the way to do it?索引是这样做的方法吗?

Index is not used for ordering documents in any way, they are telling the database to index the data so it can be searched through efficiently.索引不用于以任何方式对文档进行排序,它们告诉数据库对数据进行索引,以便可以有效地搜索它。 In Doctrine's ORM there is an @OrderBy annotation but sadly it has not made its way to the ODM (yet).在 Doctrine 的 ORM 中有一个@OrderBy注释,但遗憾的是它还没有进入 ODM(还)。 The solution would either be to support such thing natively in the ODM itself or you could use a custom collection for your embedded documents.解决方案要么是在 ODM 本身中支持这种东西,要么您可以为您的嵌入文档使用自定义集合。

Here you will find documentation for custom collections and here's a link to my package that aims to kickstart your own implementations: https://github.com/malarzm/collections .在这里你会找到自定义集合的文档,这里是我的包的链接,旨在启动你自己的实现: https : //github.com/malarzm/collections To get what you need you will need your own collection class looking somehow like this:为了得到你需要的东西,你需要你自己的集合类,看起来像这样:

class SortableCollection extends Malarzm\Collections\SortedCollection
{
    public function compare($a, $b)
    {
        return $a->getOrder() <=> $b->getOrder();
    }
}

and then plug it into your mapping:然后将其插入您的映射中:

/**
 * @ODM\EmbedMany(targetDocument=Image::class, strategy="set", customCollection=SortableCollection::class)
 * @ODM\Index(keys={"order"="asc"})
 * @Groups({"offer:read"})
 */
protected $images = [];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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