@Route - 如何确保学说也检查父实体

@Route - How to make sure doctrine also check parent entities

我的项目中有一些路线是长期 parent/child 关系的结果。

问题在于 Symfony 仅通过其 ID 搜索实体。忽略路由中的所有其他参数。

比如我有这条路线:

@Route("/projets/projet-{projet}/murs/mur-{mur}/obstacles/obstacle-{id}/", name="obstacle_edit")
editAction(Request $request, Obstacle $obstacle) {}

这里,obstacle就是我要找的实体。
mur$obstacle->getMur()
projetobstacle->getMur()->getProjet()

因此,我的form标签是这样的:

<form action="{{ path('obstacle_edit', { 'projet': obstacle.mur.projet.id, 'mur': obstacle.mur.id, 'id': obstacle.id }) }}" method="POST"></form

然而,Doctrine 运行 这个查询:

SELECT 
  t0.id AS id_1, 
  t0.nom AS nom_2, 
  t0.posx AS posx_3, 
  t0.posy AS posy_4, 
  t0.posz AS posz_5, 
  t0.dimx AS dimx_6, 
  t0.dimy AS dimy_7, 
  t0.dimz AS dimz_8, 
  t0.mur_id AS mur_id_9 
FROM 
  obstacle t0 
WHERE 
  t0.id = ?

因此,忽略路由中的其他两个参数。

如何确保其他参数不会被忽略?

您可以通过使用注释显式覆盖行为来修改实体的加载方式。参见:https://symfony.com/doc/master/bundles/SensioFrameworkExtraBundle/annotations/converters.html#fetch-via-an-expression

在您的情况下,它可能看起来像这样:

/**
 * @Route("/projets/projet-{projet}/murs/mur-{mur}/obstacles/obstacle-{id}/", name="obstacle_edit")
 * @Entity("obstacle", expr="repository.findObstacleByProjectMurAndId(projet, mur, id)")
 */
public function editAction(Request $request, Obstacle $obstacle) { ... }

您随后放入此存储库的实际查询逻辑。根据您的具体需求,这可能就像包装 findBy(['mur' => $mur, 'projet' => $projet, 'id' => $id]) 或更复杂的查询一样简单。