使用多通关系以相反方向获取实体

vhmi4jdf  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(316)

我要做的是返回一个多人关系中的实体,也做相反的操作,使用orm返回一个多人关系中的实体。
例如,如果我有两个实体 Tree 以及 Branch ,使用条令Map来查询特定树并获得其分支列表(关系是一棵树->多个分支)是相当简单的
树实体

/**
 * @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"
        }
}

这可能吗?

cedebl8k

cedebl8k1#

结果比我想象的要容易。由于Map的原因,相反的方法很简单,只需调用Map到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()
]);

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

相关问题