我有一个包含多个多对多连接的表结构。
nodes -< node_template >- templates -< placeholder_template >- placeholder
我使用 belongsToMany
方法设置我的节点、模板和占位符模型,以通过连接表链接主表。
例如
public function byFileMakerIdWithTemplates($id){
return $this->node->with('templates')->where('internal_id', '=', $id)->firstOrFail();
}
有没有一种方法可以使用 Eloquent 选择多级子节点?
即,有没有一种方法可以查询特定的 node
记录并获取 template
子记录和模板的 placeholder
记录?像这样的东西:
public function byFileMakerIdWithTemplates($id){
return $this->node->with('templates')->with('placeholders')->where('internal_id', '=', $id)->firstOrFail();
}
我知道我可以使用 DB
facade 为您编写 mysql 查询 我需要使用 JOIN
子句获取所有数据或编写代码来查找节点及其所有模板,然后通过每个模板进行 foreach 以查找占位符,但如果有一种方法可以在多维数组中将其全部干净地抓取,那就太棒了。
最佳答案
您可以使用 .
点语法急切加载深层嵌套关系:
with('relationA.relationB');
所以你会写:
public function byFileMakerIdWithTemplates($id){
return $this->node->with('templates.placeholders')->where('internal_id', '=', $id)->firstOrFail();
}
关于php - 使用 Eloquent 访问多个级别的多对多子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27681808/