简体   繁体   English

原则:与ID的多对多关系

[英]Doctrine: Many-To-Many Relationship with ID

Is it possible in a Doctrine 2 Many-To-Many relationship to NOT have a composite key from the join tables but rather to have an ID column. “ Doctrine 2多对多”关系中,可能没有联接表中的组合键 ,而是拥有ID列。

A_B A_B

ID
A_ID
B_ID

Current issue is that it orders the inserted ids by ascending order, but I need them to be in the order that they have been added from the form . 当前的问题是,它按升序对插入的ID进行排序,但是我需要它们按照从表单中添加它们的顺序。

Thanks 谢谢

Many-to-many relations aren't meant to be ordered. 多对多关系并不是要有秩序的。 If you want to order something you're introducing extra data to the joining table and it stops being a joining table but a separate entity. 如果要订购某些商品,则需要向联接表中引入额外的数据,它不再是联接表而是一个单独的实体。 So in order to order the relation you'd have to define the "joining entity" and setup many-to-one realations to both tables like that: 因此,为了排序关系,您必须定义“连接实体”并为两个表设置多对一实现,如下所示:

Table A            Table AB            Table B
ID                 A_ID                ID
                   B_ID
                   order

with AB table having many-to-one relations to A and B. AB表与A和B具有多对一关系。

yes it is possible 对的,这是可能的

Table A            Table AB           Table B
ID                 ID
                   A_ID                ID
                   B_ID
                   order

in A entity you should define: 在实体中,您应该定义:

/**
* @ORM\ManyToMany(targetEntity="\YourNameSpace\Model\Entities\B",fetch="EXTRA_LAZY")
* @ORM\JoinTable(
*      name="AB",
*      joinColumns={
*          @ORM\JoinColumn(name="B_ID", referencedColumnName="A_ID")
*      },
*      inverseJoinColumns={
*          @ORM\JoinColumn(name="B_ID", referencedColumnName="ID")
*      }
*)
*/
protected $B;

and in B entity: 在B实体中:

/**
* @ORM\ManyToOne(targetEntity="\YourNameSpace\Model\Entities\A", inversedBy="AB", fetch="EXTRA_LAZY")
* @ORM\JoinColumns({
*   @ORM\JoinColumn(name="A_ID", referencedColumnName="ID")
* })
*/
protected $A;

but if your main problem is only sorting you can add created field to your table and sort by it. 但是,如果您的主要问题只是排序,则可以将创建的字段添加到表中并对其进行排序。

->orderBy('AB.created', 'DESC')

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

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