php - 使用 Eloquent 访问多个级别的多对多子级

标签 php mysql laravel laravel-4 eloquent

我有一个包含多个多对多连接的表结构。

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/

相关文章:

php - 随机定位图像并避免重叠(没有 wordpress 插件)

php - 如何格式化多维/嵌套数组,使其仅返回整数而不返回列标题?

mysql - 在表、XML 或 JSON 中存储大文本的最佳方法?

php - laravel Eloquent 地从链接表中求和多行

php - SQLSTATE[23000] : Integrity constraint violation: Duplicate entry 'B' for key qr_codes_encoded_key_unique

laravel - 检测肉眼可见图像中的独特颜色

php - 从 PHP 页面调用时 Python 导入失败

php - 是否可以加载外部页面?

php - Openshift MYSQL Cartige IP

MySQL not null 约束不起作用