Laravel 在同一个表中返回父母的孩子
问题描述
使用 Laravel 5.1,我尝试从 MySQL 类别表创建菜单列表.我的服务提供者返回数据,但我不明白如何在 foreach 循环中创建子类别.当我执行循环时,只返回子查询的最后一行.任何指导将不胜感激.
Using Laravel 5.1, I am trying to create a menu list from a MySQL categories table. My service provider returns data, but I don't understand how to create the child categories in a foreach loop. When I perform the loop, only the last row of the child query is returned. Any guidance would be appreciated.
类别表
预期结果
viewComposerServiceProvider.php
标题视图
推荐答案
首先,你的做法是低效的.您的视图遍历每个父类别的所有子类别.如果您正确定义关系并利用 Eloquent 的预先加载,您可以更轻松地获取和访问子类别.
First of all, what you are doing is inefficient. Your view iterates through all subcategories for every parent category. If you defined relations properly and made use of Eloquent's eager loading, you could fetch and access child categories in easier way.
从定义关系开始:
一旦您正确定义了关系,您就可以获取整个类别树,如下所示:
Once you have the relations defined properly, you can fetch whole category tree like below:
不需要第二个作曲家,因为父类别已经包含子类别.
The second composer won't be needed, as parent categories already contain children.
现在,您只需要在视图中显示类别:
Now, you only need to display the categories in your view:
这篇关于Laravel 在同一个表中返回父母的孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!