Symfony / Doctrine ManyToMany以分配或保存的顺序获取记录

时间:2019-02-14 09:07:17

标签: symfony doctrine-orm symfony3.x

我有一个名为Item的实体,该实体与JoinTable的ManyToMany连接与一个名为Tags的实体

这很好。问题是,我需要按选择的确切顺序排列标签,而不是按标签ID排序,因为我现在在Item类上调用getTags()时会得到它们。有办法吗?

1 个答案:

答案 0 :(得分:1)

使用联接表定义该顺序。

Item_id | Tags_id | Order
--------+---------+------
 1      | 1       | 2
 1      | 2       | 1    <-- order for tags of item 1
 1      | 3       | 3
 -------+---------+------
 2      | 42      | 1
 2      | 1       | 2    <-- order for tags of item 2
 -------+---------+------
 3      | 3       | 1    <-- order for tags of item 3

...和等同的实体:

您要从

//MToM : Many To Many
//OToM : One To Many
//MToO : Many To One

[Item] -MToM-> [Tags]
[Tags] -MToM-> [Item]

收件人

[Item] -OToM-> [ItemTags] -MToO-> [Tags]
[Tags] -OToM-> [ItemTags] -MToO-> [Item]

而且,在您的实体类中:

class Item
{
    // some properties ...

    /**
     * @OneToMany(targetEntity="ItemTags", mappedBy="Item")
     */
    private $ItemTags; //array

    //more properties, and get/set
}

class Tags
{
    // some properties ...

    /**
     * @OneToMany(targetEntity="ItemTags", mappedBy="Tags")
     */
    private $ItemTags; //array

    //more properties, and get/set
}

class ItemTags
{
    /**
     * @ManyToOne(targetEntity="Item", inversedBy="ItemTags")
     * @JoinColumn(name="Item_id", referencedColumnName="id")
     *                   ^-----^-------------------------^^---- Make sure to use the same than in your table !
     */
    private $Item; // single Item

    /**
     * @ManyToOne(targetEntity="Tags", inversedBy="ItemTags")
     * @JoinColumn(name="Tags_id", referencedColumnName="id")
     *                   ^-----^-------------------------^^---- Make sure to use the same than in your table !
     */
    private $Tags; // single Tags

    private $Order;

    // get/set and stuff
}