gpt4 book ai didi

php - 原则 2 不坚持从拥有一方到多方的关系

转载 作者:可可西里 更新时间:2023-10-31 22:45:49 25 4
gpt4 key购买 nike

我有这个代码

// ONE to many Bidir -- inverse side
/**
* @ORM\OneToMany(targetEntity="Item", mappedBy="Room", cascade={"persist"})
**/
protected $items;

另一边

// ONE to many Bidir-- own side
/**
* @ORM\ManyToOne(targetEntity="Room", inversedBy="items")
* @ORM\JoinColumn(name="room_id", referencedColumnName="id")
**/
protected $room;

我的问题是我转到项目页面并选择 Room ,然后我可以在 Room 页面中看到预选的项目

但是如果我转到 Room 页面并尝试多选许多项目,那么这些项目就不会保留

编辑:我已经看到它只发生在 OneToMany 关系上。对于 Manyto Many,他们工作正常

编辑2:

我说的是后端区域,我可以在其中选择多个项目的表单和选择框。此表单/CRUD 代码/ Controller 由学说生成。所以我不需要添加任何额外的功能。不管怎样,这是我的 Controller 代码

$editForm   = $this->createForm(new RoomType(), $entity);


$request = $this->getRequest();

$editForm->bindRequest($request);
if ($editForm->isValid()) {
$em->persist($entity);
$em->flush();

当我尝试像这样遍历 Controller 时

foreach($entity->getItems() as $item)
echo $item;

然后我可以在那里看到你所有的项目。所以这意味着所有项目都在主要对象中,但它不会持久化它们。我不知道为什么。

如果有欠、反面问题。我怎样才能改变从逆向和逆向拥有的关系

最佳答案

根据您在注释中的评论,您的代码是错误的。

这是拥有方,因为您指定了inversedBy 属性:

/**
* ONE to many Bidir-- Inverse side
* @ORM\ManyToOne(targetEntity="Room", inversedBy="items")
* @ORM\JoinColumn(name="room_id", referencedColumnName="id")
**/
protected $room;

这是反面(因为它有mappedBy属性):

/**
* ONE to many Bidir -- owning side
* @ORM\OneToMany(targetEntity="Item", mappedBy="Room", cascade={"persist"})
**/
protected $items;

所以你的代码说:Item 是拥有方,Room 是相反方。

The owning side of a bidirectional relationship must refer to its inverse side by use of the inversedBy attribute of the OneToOne, ManyToOne, or ManyToMany mapping declaration. The inversedBy attribute designates the field in the entity that is the inverse side of the relationship.

让它更干净:

The owning side has to use the inversedBy attribute of the OneToOne, ManyToOne, or ManyToMany mapping declaration. The inversedBy attribute contains the name of the association-field on the inverse-side.

同时,对于反面:

The inverse side of a bidirectional relationship must refer to its owning side by use of the mappedBy attribute of the OneToOne, OneToMany, or ManyToMany mapping declaration. The mappedBy attribute designates the field in the entity that is the owner of the relationship.

再一次:

The inverse side has to use the mappedBy attribute of the OneToOne, OneToMany, or ManyToMany mapping declaration. The mappedBy attribute contains the name of the association-field on the owning side.

另外,另一个重要的考虑因素:

ManyToOne is always the owning side of a bidirectional assocation.

OneToMany is always the inverse side of a bidirectional assocation

因此,对于从反面(房间)持久化项目,您必须检查已选择/取消选择了哪个项目,以及房间是否已包含该项目。

关于php - 原则 2 不坚持从拥有一方到多方的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12001979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com