从具有相同列名的 Symfony 路由注释中获取多个实体

Get Multiple Entities from Symfony route annotation with the same column name

我有两个学说实体。项目和故事,它们都有一个唯一的列名称别名。我想获取项目和故事实体(在这种情况下,我实际上只想要 Story 对象,但项目别名将是动态的)。我尝试使用 @Entity 属性:

    /**
     * @Route("/project/{Alias}/{StoryAlias}", name="front-project-story-page" )
     * @Entity("Story", expr="repository.findBy(['Alias'=>StoryAlias])")
     */
    public function FrontProjectStoryPage(Project $project,Story $story)
    {
     ....
    }

但是提示这个错误

An exception has been thrown during the rendering of a template 
("[Semantical Error] Annotation @Entity is not allowed to be declared on method. 
You may only use this annotation on these code elements: CLASS in /home/../config/routes/../../src/Controller/ 
(which is being imported from "/home/../config/routes/annotations.yaml"). 
Make sure annotations are installed and enabled.").

如何获取可能具有相同列名的实体?

根据文档你可以这样做

mapping: Configures the properties and values to use with the findOneBy() method: the key is the route placeholder name and the value is the Doctrine property name:

/**
 * @Route("/blog/{date}/{slug}/comments/{comment_slug}")
 * @ParamConverter("post", options={"mapping": {"date": "date", "slug": "slug"}})
 * @ParamConverter("comment", options={"mapping": {"comment_slug": "slug"}})
*/
public function showComment(Post $post, Comment $comment)
{
}

我相信您使用的是 Doctrine\ORM\Annotation\Entity 而不是 Sensio\Bundle\FrameworkExtraBundle\Configuration\Entity

然而,正如其他人所提到的,使用 Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter 也可以达到相同的结果:

    /**
     * @Route("/project/{alias}/{story-alias}", name="front-project-story-page" )
     *
     * @ParamConverter("project", options={"mapping": {"alias": "alias"}})
     * @ParamConverter("story", options={"mapping": {"story-alias": "alias"}})
     */
    public function FrontProjectStoryPage(Project $project,Story $story)
    {
     ....
    }

阅读更多:https://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/converters.html#doctrineconverter-options