【问题标题】:Fetching entities in the opposite direction with Doctrine ORM ManyToOne Relationship使用 Doctrine ORM ManyToOne 关系在相反方向获取实体
【发布时间】:2018-11-02 20:57:04
【问题描述】:

我想要完成的是返回一个多对一关系中的实体,并执行相反的操作并使用 Doctrine ORM 返回一个单对多关系中的实体。

例如,如果我有两个实体 TreeBranch,则使用 Doctrine 映射来查询特定树并获取其分支的列表是相当简单的(其中关系是一棵树 -> 多个分支)

树实体

/**
 * @ORM\OneToMany(targetEntity="Branches", mappedBy="tree_id")
 */
protected $branches;

分支实体

/**
 * @ORM\ManyToOne(targetEntity="Branches", inversedBy="tree")
 * @ORM\JoinColumn(name="tree", referencedColumnName="id")
 */
protected $tree;

在此示例中,当我在 TreeController 上查询时,我会以以下格式返回 JSON:

{
    "id": "1",
    "name": "TreeOne"
    "branches": [
        {
            "id": "1",
            "name": "BranchOne"
        },
        {
            "id": "1",
            "name": "BranchTwo"
        },
        ...
    ]
}

问题是,我如何通过调用 BranchController 进行反向操作并获取分支及其关联的树,以便调用 API 的结果是:

{
    "id": "1",
    "name": "BranchOne"
    "tree": {
            "id": "1",
            "name": "TreeOne"
        }
}

这可能吗?

【问题讨论】:

    标签: mysql orm annotations doctrine mapping


    【解决方案1】:

    事实证明这比我想象的要容易。由于映射,反向操作就像调用映射到 Join 注释的 setter/getter 一样简单。比如:

    public function setTree(?\Tree $tree = null): self
    {
        $this->tree = $tree;
    
        return $this;
    }
    
    public function getTree(): ?Tree
    {
        return $this->tree;
    }
    

    然后在将数据返回给前端客户端应用程序的函数中,您必须简单地调用上面的 getter:

    return array_filter([
        'id' => this->getId(),
        'name' => $this->getName(),
        'tree' => $this->getTree()
    ]);
    

    您将获得问题中要求的格式的数据!

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 1970-01-01
      • 2021-04-23
      • 2017-07-27
      • 1970-01-01
      • 2014-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多